Alex
Alex

Reputation: 68482

call_user_func on methods

Is there any difference between:

$callback = array(&$this, 'method');
$callback[0]->$callback[1]($args);

and

call_user_func(array(&$this, 'method'), $args);

?

Upvotes: 4

Views: 238

Answers (3)

Narf
Narf

Reputation: 14752

I haven't really seen the first example in use, but it seems valid and should be faster than call_user_func() as you don't have the overhead of calling another function.

UPDATE:

Also, you can't do this with call_user_func() if you have enabled the E_STRICT error level:

// ...

public function &example($foo)
{
    $this->bar = 'foo';
    return $this->bar;
}

// ...

$dummy = &$callback[0]->$callback[1]($args);

In that case, call_user_func() will trigger something like this to appear:

PHP Strict Standards: Only variables should be assigned by reference in php shell code on line X

Upvotes: 1

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

No difference, but i prefer the second one for readability. First one is less clear and takes two lines...

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

No, there is no difference between calling a variable method/function and using call_user_func. I haven't run across a circumstance where I needed the latter. By the way, you don't need to pass $this by reference; all objects are automatically passed by reference.

Upvotes: 2

Related Questions