代码之家  ›  专栏  ›  技术社区  ›  mk.

如何在PHP中的类中创建分派表?

  •  2
  • mk.  · 技术社区  · 16 年前

    假设我有一个带有私人调度表的班级。

    $this->dispatch = array(
        1 => $this->someFunction,
        2 => $this->anotherFunction
    );
    

    如果我打电话

    $this->dispatch[1]();
    

    我得到一个错误,该方法不是字符串。当我把它做成这样一根绳子时:

    $this->dispatch = array(
        1 => '$this->someFunction'
    );
    

    这产生 致命错误:调用未定义的函数$this->someFunction()。

    我还尝试使用:

    call_user_func(array(SomeClass,$this->dispatch[1]));
    

    导致 消息:call_user_func(someClass::$this->someFunction)[函数。call user func]:第一个参数应该是有效的回调 .

    编辑: 我意识到这并没有真正意义,因为它调用了某个类::$this,而$this是someclass。我尝试过几种方法,其中数组包含

    array($this, $disptach[1])
    

    这仍然不能满足我的需要。

    结束编辑

    如果我没有类,只有一个带有一些函数的分派文件,那么这就可以工作。例如,这是可行的:

    $dispatch = array(
        1 => someFunction,
        2 => anotherFunction
    );
    

    我想知道是否有一种方法可以将这些方法作为私有方法保存在类中,但仍然将它们与调度表一起使用。

    2 回复  |  直到 15 年前
        1
  •  8
  •   Allain Lalonde    16 年前

    您可以在分派中存储方法的名称,例如:

    $this->dispatch = array('somemethod', 'anothermethod');
    

    然后使用:

    $method = $this->dispatch[1];
    $this->$method();
    
        2
  •  5
  •   Waquo    16 年前

    调用用户函数系列的工作方式如下:

    $this->dispatch = array('somemethod', 'anothermethod');
    ...
    call_user_func(array($this,$this->dispatch[1]));