Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there differences between call_user_func() and $var()?

Tags:

php

Is there any differences between call_user_func() and its syntactic sugar version...

// Global function

$a = 'max';

echo call_user_func($a, 1, 2); // 2
echo $a(1, 2); // 2

// Class method

class A {

   public function b() {
     return __CLASS__;
   }

   static function c() {
      return 'I am static!';
   }

}

$a = new A;
$b = 'b';

echo call_user_func(array($a, $b)); // A
echo $a->$b(); // A

// Static class method

$c = 'c';

echo call_user_func(array('A', $c)); // I am static!
echo a::$c(); // I am static!

codepad.

Both output the same, but I was recently hinted (10k+ rep only) that they are not equivalent.

So, what, if any, are the differences?

like image 400
alex Avatar asked Dec 17 '22 17:12

alex


1 Answers

First difference I can think of is that call_user_func() runs method as a callback.

This means you can use a closure, eg

echo call_user_func(function($a, $b) {
    return max($a, $b);
}, 1, 2);

This would be more of an implementation difference versus a usage or performance (execution) one though.

like image 188
Phil Avatar answered Jan 09 '23 14:01

Phil