【发布时间】:2018-04-20 07:50:51
【问题描述】:
我可以将 Foo 类的方法绑定到 Bar 类吗?为什么下面的代码会抛出警告“无法将方法 Foo::say() 绑定到类 Bar 的对象”?使用函数而不是方法代码可以正常工作。
附:我知道扩展)这不是实际问题,只是想知道将非静态方法绑定到另一个类是否真实
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();
下面的代码可以正常工作
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();
【问题讨论】:
-
你可以扩展到那个类
-
不确定,但可以尝试将
say()更改为静态? -
我知道)但是这个关于闭包和绑定的问题
-
我重新审视了你的问题,但我不明白你在问什么。你是什么意思:“只想知道将非静态方法绑定到另一个类是真的吗”?
-
对我来说很明显..在 JS 中经常使用它