创建 OOP 回调

Creating OOP Callbacks

我正在尝试了解如何将匿名函数与 OOP 回调方法一起使用。我的 class 看起来像这样:

class Example
{
    protected $Callbacks = array();

    public function set(
        $foo,$bar
    ) {
        $this->Callbacks[$foo] = $bar;
    }

    public function get(
        $foo
    ) {
        return $this->Callbacks[$foo];
    }
}

要添加新的回调,我只需执行以下操作:

$example = new Example;
$example->set(
     'example', function() {
         return 'hello';
     });

然而,当我想使用该功能时,当我 运行 时没有任何反应:

echo $example->get('example');

任何人都可以帮助并解释如何以 OOP 方式创建回调吗?

也谢谢@PeeHaa,我终于解决了这个问题。

当我检索函数时,它还处于关闭状态,还没有被执行。根据您的 PHP 版本,您可以执行以下任一操作:

$execute = $example->get('example')();
echo $execute;

echo $example->get('example')();

您可以这样调用函数:

echo $example->get('example')();

但我觉得很难看。您也可以为此目的使用魔法方法。但这也不是最佳做法。

class Example
{
    protected $Callbacks = array();

    public function __set($name, $value)
    {
        $this->Callbacks[$name] = $value;
    }

    public function __call($name, array $arguments)
    {
        if (!isset($this->Callbacks[$name])) {
            trigger_error('Call to undefined method ' . get_class($this) . "::$name()", E_USER_ERROR);
        }
        return $this->Callbacks[$name]($arguments);
    }
}

$example = new Example();
$example->example = function() {
    return 'hello';
};

echo $example->example();