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
// St开发者_开发技巧atic 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?
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.
I honestly can't find much of a difference between the two. They basically do the same thing, but the only differences I can find is that call_user_func
takes over 2× longer to complete than variable functions (calling an empty function).
Another thing is that the error handlers are different, if you use a non-existent callback function, the variable function would output a fatal error and halt the script while call_user_func
would output a warning but continue the script.
Also when passing parameters through the function, using variable functions provides a little more detail in the error in relation to 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):
Warning: Missing argument 2 for asdf(), called in G:\test.php on line 10 and defined in G:\test.php on line 3
These errors are collected from Command-Line Interface (CLI) tests, the display of errors obviously depends on your configuration.
精彩评论