PHP5:类对象之间的回调
我试图理解PHP5的关闭/回调可以走多远,但我目前陷入了一个“为什么这不起作用”的玻璃箱中 在下面的示例中,我知道在回调中使用PHP5:类对象之间的回调,php,oop,closures,Php,Oop,Closures,我试图理解PHP5的关闭/回调可以走多远,但我目前陷入了一个“为什么这不起作用”的玻璃箱中 在下面的示例中,我知道在回调中使用$this是行不通的(尤其是当范围发生变化时),它只是向您展示我希望如何使用回调/闭包 class Customer { public $name = ''; public $callback = NULL; function __construct($name) { $this->name = $name; } function wh
$this
是行不通的(尤其是当范围发生变化时),它只是向您展示我希望如何使用回调/闭包
class Customer {
public $name = '';
public $callback = NULL;
function __construct($name) {
$this->name = $name;
}
function when_enters($callback) {
$this->callback = $callback;
}
function enter_store() {
if(is_callable($this->callback))
call_user_func($this->callback);
}
}
class Salesman {
public $customer = NULL;
function add_customer(&$customer) {
$this->customer =& $customer;
$this->customer->when_enters(function() {
$this->greet_customer();
});
}
function greet_customer() {
echo "Hello, {$this->customer->name}!";
}
}
$salesman = new Salesman();
$customer = new Customer('John');
$salesman->add_customer(&$customer);
$customer->enter_store();
通过将saller
实现为一个静态类,并将回调函数设置为saller::greet_customer
,而不是$this->greet_customer()
,我已经能够在功能上重现这个基本函数
基本上,我想知道的是。。。使用对象实例,这种功能可能吗?在php中,
call\u user\u func
可以接受两元素数组来调用类上的方法。因此,如果您这样做:
$this->customer->when_enters(array($this,'greet_customer'));
它会做你想做的事。PHP 5.3.0或更高版本上的另一种选择是使用闭包和$this
的本地副本:
$this_copy=$this;
$this->customer->when_enters(function() use ($this_copy) {
$this_copy->greet_customer();
});
我有一些好消息,也有一些坏消息 好消息是,PHP的下一个主要版本(5.4?)将允许匿名函数成为类的属性,并且可以在不受限制的情况下调用,等等 坏消息是,似乎没有人知道PHP主干何时会变成发行版 现在,由于您无法在匿名函数中实际引用
$this
,因此您可以在此处执行的操作非常有限。一个选项是将当前对象传递给函数:
function enter_store() {
if(is_callable($this->callback))
call_user_func($this->callback, $this);
}
虽然这将起作用,并允许您从函数中戳出对象,但您将仅限于标记为
public
的方法和属性。这可能是您的问题,也可能不是。谢谢您的链接。这真的帮了大忙,我还找到了很多关于这个主题的书。这让我想到了,这与@Anomie指出的解决方法几乎完全相同。必须把它给他们。。。但再次感谢。:)