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