2014-02-23 32 views
0

在这个例子中;如果我打电话给wash_hands,那么它将首先执行$this->eat(),然后$this->log()php pass函数引用另一个函数在执行时返回

但我真正想要的是$this->log首先被执行,然后$this->eat()

function log($msg,$return=null){ 
//..do some logic 

return $return; 
} 

function eat(){ 
//...start eating 
} 

function wash_hands(){ 
//...wash hands 
return $this->log('hand washed',$this->eat()); 
} 

是有办法做到这一点,它仍然即使工作..

日志()函数在另一类

eat()是与wash_hands同类的私有/受保护的方法吗?

+0

如果'log'使用eat的结果作为参数,你怎么能先调用'log'如果'log'不需要参数为什么没有你只需要调用日志然后返回'吃'的结果? – Jim

回答

0

正如您发现的那样,$this->eat()立即调用该方法。 Unfortunateley $this->eat不是对函数的引用,因为语法对于属性$eat而言是相同的。但是你可以有一个参考方法形式array($object, $method)调用变量:

$this->log('hand washed', array($this, 'eat')); 

可以这样使用:

function log($msg,$return=null) { 
    // ... 
    // now calling the passed method 
    if (is_callable($return)) { 
     return $return(); 
    } 
} 

但是:

是有办法要做到这一点,它仍然会工作,即使..

log()函数是在另一类

eat()是与wash_hands同类的私有/受保护的方法吗?

如果不以某种方式公开私有函数,这是不可能的。

更新:

随着Closure binding在PHP 5.4,你实际上可以通过私有函数:

$callback = function() { return $this->eat(); } 
$this->log('hand washed', $callback->bindTo($this)); 
0

你想可以通过简单地调用该方法之后获得的行为:

function wash_hands(){ 
    //...wash hands 
    $this->log('hand washed'); 
    return $this->eat(); 
} 
相关问题