我可以将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)
当前不支持此功能。如果要将闭包绑定到新对象,则它一定不能是假闭包,否则新对象必须与旧对象(源)兼容。
因此,什么是假闭包:假闭包是从创建的闭包Closure::fromCallable。
这意味着,您可以通过两种方法来解决问题:
Bar必须与-的类型兼容,Foo因此请尽可能Bar
扩展from Foo。
使用非绑定函数,例如匿名函数,静态函数或类之外的函数。