假设我有一个带有私有(private)调度表的类。
$this->dispatch = array(
1 => $this->someFunction,
2 => $this->anotherFunction
);
如果我随后打电话
$this->dispatch[1]();
我收到一个错误,该方法不是字符串。当我把它变成这样的字符串时:
$this->dispatch = array(
1 => '$this->someFunction'
);
这会产生 fatal error :调用未定义的函数 $this->someFunction()
我也尝试过使用:
call_user_func(array(SomeClass,$this->dispatch[1]));
导致消息:call_user_func(SomeClass::$this->someFunction) [function.call-user-func]:第一个参数预计是有效的回调。
编辑:我意识到这并没有什么意义,因为当 $this 是 SomeClass 时它正在调用 SomeClass::$this 。我尝试了几种方法,数组包含
array($this, $disptach[1])
这仍然没有达到我的需要。
结束编辑
如果我没有类并且只有一个包含某些函数的调度文件,则此方法有效。例如,这有效:
$dispatch = array(
1 => someFunction,
2 => anotherFunction
);
我想知道是否有一种方法可以将它们保留为类中的私有(private)方法,但仍将它们与调度表一起使用。
最佳答案
您可以将方法的名称存储在调度中,例如:
$this->dispatch = array('somemethod', 'anothermethod');
然后使用:
$method = $this->dispatch[1];
$this->$method();
关于php - 如何在 PHP 的类中创建调度表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/306272/