PHP将方法绑定到另一个类

emp*_*y26 5 php php-7

我可以将Foo类的方法绑定到Bar类吗?为什么下面的代码引发警告“无法将方法Foo :: say()绑定到Bar类的对象”?用函数代替方法代码可以正常工作。

PS我知道有关扩展)这不是一个实际的问题,只是想知道将非静态方法绑定到另一个类是真的

class Foo {

    public $text = 'Hello World!';

    public function say() {
        echo $this->text;
    }

}

class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable(array(new Foo, 'say'));
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();
Run Code Online (Sandbox Code Playgroud)

下面的代码工作正常

 function say(){
    echo $this->text;
 }
 class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable('say');
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();
Run Code Online (Sandbox Code Playgroud)

Phi*_*ipp 5

当前不支持此功能。如果要将闭包绑定到新对象,则它一定不能是假闭包,否则新对象必须与旧对象()兼容。

因此,什么是假闭包假闭包是从创建的闭包Closure::fromCallable

这意味着,您可以通过两种方法来解决问题:

  1. Bar必须与-的类型兼容,Foo因此请尽可能Bar 扩展from Foo

  2. 使用非绑定函数,例如匿名函数,静态函数或类之外的函数。

  • 要澄清“当前”部分:永远不会支持。我们在PHP 7.1中特别禁止这样做。以前,可以执行这种重新绑定(当然,可以使用ReflectionMethod :: getClosure()而不是仅在PHP 7.1中添加的Closure :: fromCallable()),但是现在不再允许这样做。 (5认同)