php传递函数引用返回时要执行的另一个函数

时间:2014-02-23 12:38:10

标签: php oop function-pointers

在这个例子中;如果我调用wash_hands,它将首先执行$this->eat()然后$this->log()

但我真正想要的是$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());
}

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

log()函数在另一个类

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

2 个答案:

答案 0 :(得分: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相同类的私有/受保护的方法吗?

如果不以某种方式暴露私人功能,这是不可能的。

<强>更新

PHP 5.4中的Closure binding实际上可以传递私有函数:

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

答案 1 :(得分:0)

您可以通过以下方式调用该方法获得所需的行为:

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