PHP call_user_func vs. just calling function

前端 未结 8 1578
我寻月下人不归
我寻月下人不归 2020-12-04 08:06

I\'m sure there\'s a very easy explanation for this. What is the difference between this:

function barber($type){
    echo \"You wanted a $type haircut, no         


        
8条回答
  •  死守一世寂寞
    2020-12-04 08:40

    When using namespaces, call_user_func() is the only way to run a function you don't know the name of beforehand, for example:

    $function = '\Utilities\SearchTools::getCurrency';
    call_user_func($function,'USA');
    

    If all your functions were in the same namespace, then it wouldn't be such an issue, as you could use something like this:

    $function = 'getCurrency';
    $function('USA');
    

    Edit: Following @Jannis saying that I'm wrong I did a little more testing, and wasn't having much luck:

    Bar: ".\Foo\Bar::getBar()."";
        // outputs 'Bar: Bar'
        $function = '\Foo\Bar::getBar';
        echo "

    Bar: ".$function()."

    "; // outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()' $function = '\Foo\Bar\getBar'; echo "

    Bar: ".$function()."

    "; // outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()' }

    You can see the output results here: https://3v4l.org/iBERh it seems the second method works for PHP 7 onwards, but not PHP 5.6.

提交回复
热议问题