如何在PHP中的类中创建调度表?

mk.*_*mk. 2 php dispatch-table

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

$this->dispatch = array(
    1 => $this->someFunction,
    2 => $this->anotherFunction
);
Run Code Online (Sandbox Code Playgroud)

如果我再打电话

$this->dispatch[1]();
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,该方法不是一个字符串.当我把它变成这样的字符串时:

$this->dispatch = array(
    1 => '$this->someFunction'
);
Run Code Online (Sandbox Code Playgroud)

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

我也试过用:

call_user_func(array(SomeClass,$this->dispatch[1]));
Run Code Online (Sandbox Code Playgroud)

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

编辑:我意识到这并没有真正意义,因为当这是SomeClass时它调用SomeClass :: $ this.我已经尝试了几种方法,包含数组

array($this, $disptach[1])
Run Code Online (Sandbox Code Playgroud)

这仍然没有达到我的需要.

结束编辑

如果我没有类并且只有一个包含某些函数的调度文件,则此方法有效.例如,这有效:

$dispatch = array(
    1 => someFunction,
    2 => anotherFunction
);
Run Code Online (Sandbox Code Playgroud)

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

All*_*nde 8

您可以在调度中存储方法的名称,如:

$this->dispatch = array('somemethod', 'anothermethod');
Run Code Online (Sandbox Code Playgroud)

然后使用:

$method = $this->dispatch[1];
$this->$method();
Run Code Online (Sandbox Code Playgroud)


Waq*_*quo 5

call_user_func*-Family函数应该像这样工作:

$this->dispatch = array('somemethod', 'anothermethod');
...
call_user_func(array($this,$this->dispatch[1]));
Run Code Online (Sandbox Code Playgroud)