无法绑定可调用对象关闭

时间:2018-10-04 12:02:31

标签: php oop closures php-7

在路由器库上工作时,我试图启用不同的方法来将回调传递给路由处理程序。这些方法之一是使用魔术__invoke方法的类。此类的实例标识为可调用(is_callable($obj) === true),因此我想您可以将它们传递给Closure::fromCallable并将它们绑定到作用域对象。
但是,如下面的示例所示,在闭包上调用bindTo不起作用,而且我不明白这里出了什么问题。

class Invokable {
    public function __invoke() {
        return $this->foo + 20;
    }
}

class Context {
    public $foo = 22; 
}

$context = new Context(); // Create arbitrary object to bind the closure to
$test = new Invokable(); // Create instance of the single-shot class

$closure = Closure::fromCallable($test); // This is fine and returns a callable 
$boundClosure = $closure->bindTo($context); // <-- Crashes

echo $boundClosure(); // Expected ouput: 42

在PHP 7.3.0中执行此代码将导致以下输出:

Warning:     Cannot bind method Invokable::__invoke() to object of class Context
Fatal error: Uncaught Error: Function name must be a string

0 个答案:

没有答案
相关问题