Are there any differences between call_user_func () and $ var ()?

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

 // 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 are output the same, but I was recently outlined (only 10k + rep) that they are not equivalent.

So what, if any, are the differences?

+4
source share
2 answers

The first difference I can think of is that call_user_func() executes the method as a callback.

That means you can use closure like

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

It would rather be a difference in implementation compared to use or execution (execution), though.

+5
source

Honestly, I cannot find many differences between them. They basically do the same, but the only differences I can find is that call_user_func takes more than 2 ร— longer than variables (calling an empty function).

Another thing is that error handlers are different from each other, if you use a nonexistent callback function, the variable function will throw a fatal error and stop the script, and call_user_func will display a warning, but continue the script.

Also, passing parameters through a function, using variable functions gives a bit more error information regarding line numbers:

 function asdf($a, $b) { return(1); } 

call_user_func ('asdf', 1) :

Warning: Missing argument 2 for asdf () in G: \ test.php on line 3

-

$ a = 'ASDF'; $ a ($ a, 1) :

A warning. There is no argument 2 for asdf () called in G: \ test.php on line 10 and is defined in G: \ test.php on line 3

These errors are compiled from command line interface (CLI) tests; the error display obviously depends on your configuration.

+6
source

Source: https://habr.com/ru/post/1340569/


All Articles