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

如何在PHP中的类中创建分派表?,php,dispatch-table,Php,Dispatch Table,假设我有一个带有私人调度表的类 $this->dispatch = array( 1 => $this->someFunction, 2 => $this->anotherFunction ); 如果我那时打电话 $this->dispatch[1](); 我得到一个错误,该方法不是字符串。当我把它做成这样的字符串时: $this->dispatch = array( 1 => '$this->someFuncti

假设我有一个带有私人调度表的类

$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\u user\u func(SomeClass::$this->someFunction)[function.call user func]:第一个参数应该是有效的回调

编辑:我意识到这没有什么意义,因为它调用了SomeClass::$this,而$this是SomeClass。我尝试了几种方法,数组包含

array($this, $disptach[1])
这仍然不能满足我的需要

结束编辑

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

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

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

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

$this->dispatch = array('somemethod', 'anothermethod');
然后使用:

$method = $this->dispatch[1];
$this->$method();

call_user_func*-函数族的工作原理如下:

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

我想我更喜欢你的方法,因为它不需要先取消对方法的引用。