PDA

Click to See Complete Forum and Search --> : [RESOLVED] Callback Functions


tomcatexodus
Jun 15th, 2010, 11:33 PM
I'm having an issue with callback functions, specifically storing them...

If I have a class:


class myObject{

protected $callback;

public function __construct($callbackFunction){
$this->callback = $callbackFunction;
.
.
.
}

public function doSomething($args){
if(is_callable($this->callback)){
return $this->callback($args);
}
}

}


And I try doing this:



function foo($arg){
return strtoupper($arg);
}

$myNewObject = new myObject("foo");
echo $myNewObject->doSomething("bar"); //should echo BAR


I end up with an error:


Fatal Error: Call to undefined method MyObject::callback() in ...


The is_callable() is succeeding, but the actual callback function call is the line failing with that error.

This isn't exactly what I'm doing obviously, but its a replicate of the code. Any ideas?

kows
Jun 16th, 2010, 12:04 AM
you have to tell PHP that you're calling $this->callback (the variable), not the method callback() of $this.

return {$this->callback}();

tomcatexodus
Jun 16th, 2010, 12:28 AM
return {$this->callback}(empty($this->buffer) ? $template : $this->buffer);
It's not liking that.. unexpected {

I wanna stray from call_user_func() too, because that is hugely processor intensive.

kows
Jun 16th, 2010, 12:35 AM
oh. store it in a non-class variable then:

$callback = $this->callback;
$callback();