PHP将方法绑定到另一个类 [英] PHP binding method to another class
问题描述
我可以将Foo类的方法绑定到Bar类吗?为什么下面的代码引发警告无法将方法Foo :: say()绑定到Bar类的对象"?用函数代替方法代码可以正常工作.
Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.
P.S.我知道扩展),这不是一个实际的问题,只是想知道将非静态方法绑定到另一个类是真的
P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class
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();
下面的代码可以正常工作
Code below works fine
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();
推荐答案
当前不支持此功能.如果要将闭包绑定到新对象,则它不能是假闭包,否则新对象必须与旧对象兼容(
This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).
所以,什么是假闭包:假闭包是从Closure::fromCallable
创建的闭包.
So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable
.
这意味着,您有两个解决问题的方法:
This means, you have two options to fix your problem:
-
Bar
必须与Foo
的类型兼容-因此只需使Bar
从Foo
扩展.
Bar
must be compatible with the type ofFoo
- so just makeBar
extend fromFoo
, if possible.
使用非绑定函数,例如匿名函数,静态函数或类外部函数.
Use unbound functions, like annonymous, static or functions outside of classes.
这篇关于PHP将方法绑定到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!