duanbipu7601 2011-03-06 05:52
浏览 32
已采纳

PHP5:类对象之间的回调

I am trying to understand how far I can go with PHP5's closures/callbacks, but I am currently trapped in a glass case of "why doesn't this work".

In the following example, I understand that the use of $this in a callback (especially when the scope changes) isn't going to work, it's just there to show you how I hope to be able to use callbacks/closures.

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();

I have been able to reproduce this basic functionally by implementing Salesman as a static class and setting the callback function as Salesman::greet_customer instead of $this->greet_customer().

Basically, what I want to know is... using object instances, is this kind of functionality possible?

  • 写回答

2条回答 默认 最新

  • dongyu9263 2011-03-06 06:02
    关注

    In php, call_user_func can accept a two-element array to call a method on a class. So if you do this:

    $this->customer->when_enters(array($this,'greet_customer'));
    

    it will do what you want. Another alternative on PHP 5.3.0 or greater is to use a closure along with a local copy of $this:

    $this_copy=$this;
    $this->customer->when_enters(function() use ($this_copy) {
        $this_copy->greet_customer();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效