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

标签 php dispatch-table

假设我有一个带有私有(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/

相关文章:

perl - 如何在Perl中实现调度表?

php - 即使 id 匹配,SQL INNER JOIN 也仅从第二个表中选择最后一行

php - 使用brew更新El Capitan php版本

php - 如何消除 Smarty {block} 中的空格?

php - 尝试将 MySql 数据库行转换为链接,以便用户可以选择他们想要查看的内容

php - Laravel 5.2 - 如何返回 PDF 作为 JSON 响应的一部分

java - 如何查看继承的Java类的虚函数表

Java:具有数百万项的 HashMap 性能与 if-else 搜索数值范围