Question

in this example; if i call wash_hands then it will first execute $this->eat() then $this->log().

but what i really want is that $this->log to be executed first then $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());
}

is there a way to do it and it still would work even if ..

log() function is in another class

eat() is a private/protected methode of same class as wash_hands ?

Was it helpful?

Solution

As you noticed, $this->eat() calls the method immediately. Unfortunateley $this->eat is not a reference to the function because the syntax would be the same for a property $eat. But you can have callable variables that reference to methods in the form array($object, $method):

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

which can be used like that:

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

But:

is there a way to do it and it still would work even if ..

log() function is in another class

eat() is a private/protected methode of same class as wash_hands ?

that's not possible without exposing the private function in one way or another.

Update:

With Closure binding in PHP 5.4 you actually can pass the private function:

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

OTHER TIPS

The behavior you want can be obtained by simply calling the method afterwards:

function wash_hands(){
    //...wash hands
    $this->log('hand washed');
    return $this->eat();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top