PHP call_user_func 与仅调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1596221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:13:22  来源:igfitidea点击:

PHP call_user_func vs. just calling function

phpfunction

提问by jay

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 problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");

... and this (and what are the benefits?):

......还有这个(以及有什么好处?):

function barber($type){
    echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');

采纳答案by Kai

Always use the actual function name when you know it.

当您知道时,请始终使用实际的函数名称。

call_user_funcis for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.

call_user_func用于调用您事先不知道名称的函数,但效率低得多,因为程序必须在运行时查找函数。

回答by Lucas Oman

Although you can call variable function names this way:

虽然您可以通过这种方式调用变量函数名:

function printIt($str) { print($str); }

$funcname = 'printIt';
$funcname('Hello world!');

there are cases where you don't know how many arguments you're passing. Consider the following:

在某些情况下,您不知道传递了多少参数。考虑以下:

function someFunc() {
  $args = func_get_args();
  // do something
}

call_user_func_array('someFunc',array('one','two','three'));

It's also handy for calling static and object methods, respectively:

分别调用静态和对象方法也很方便:

call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);

回答by Brian Schroth

the call_user_funcoption is there so you can do things like:

call_user_func选项在那里,因此您可以执行以下操作:

$dynamicFunctionName = "barber";

call_user_func($dynamicFunctionName, 'mushroom');

where the dynamicFunctionNamestring could be more exciting and generated at run-time. You shouldn't use call_user_func unless you have to, because it is slower.

其中dynamicFunctionName字符串可以更加精彩,并在运行时产生的。你不应该使用 call_user_func 除非你必须,因为它更慢。

回答by pivotal

I imagine it is useful for calling a function that you don't know the name of in advance... Something like:

我想这对于调用一个你事先不知道名称的函数很有用......像:

switch($value):
{
  case 7:
  $func = 'run';
  break;
  default:
  $func = 'stop';
  break;
}

call_user_func($func, 'stuff');

回答by uingtea

There is no benefits calling the function like that because I think it mainly used to call "user" function (like plugin) because editing core file is not good option. here are dirty example used by Wordpress

这样调用函数没有任何好处,因为我认为它主要用于调用“用户”函数(如插件),因为编辑核心文件不是一个好的选择。这是 Wordpress 使用的脏示例

<?php
/* 
* my_plugin.php
*/

function myLocation($content){
  return str_replace('@', 'world', $content);
}

function myName($content){
  return $content."Tasikmalaya";
}

add_filter('the_content', 'myLocation');
add_filter('the_content', 'myName');

?>

...

...

<?php
/*
* core.php
* read only
*/

$content = "hello @ my name is ";
$listFunc = array();

// store user function to array (in my_plugin.php)
function add_filter($fName, $funct)
{
  $listFunc[$fName]= $funct;
}

// execute list user defined function
function apply_filter($funct, $content)
{
  global $listFunc;

  if(isset($listFunc))
  {
    foreach($listFunc as $key => $value)
    {
      if($key == $funct)
      {
        $content = call_user_func($listFunc[$key], $content);
      }
    }
  }
  return $content;
}

function the_content()
{
  $content = apply_filter('the_content', $content);
  echo $content;
}

?>

....

....

<?php
require_once("core.php");
require_once("my_plugin.php");

the_content(); // hello world my name is Tasikmalaya
?>

output

输出

hello world my name is Tasikmalaya

回答by mils

With PHP 7 you can use the nicer variable-function syntax everywhere. It works with static/instance functions, and it can take an array of parameters. More info at https://trowski.com/2015/06/20/php-callable-paradox

使用 PHP 7,您可以在任何地方使用更好的变量函数语法。它与静态/实例函数一起工作,并且可以接受一组参数。更多信息请访问https://trowski.com/2015/06/20/php-callable-paradox

$ret = $callable(...$params);

回答by SilentGhost

in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.

在您的第一个示例中,您使用的函数名称是一个字符串。它可能来自外部或即时确定。也就是说,您不知道在创建代码时需要运行什么函数。

回答by ThomasRedstone

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

使用命名空间时, call_user_func() 是运行事先不知道名称的函数的唯一方法,例如:

$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:

编辑:在@Jannis 说我错了之后,我做了更多测试,但运气不佳:

<?php
namespace Foo {

    class Bar {
        public static function getBar() {
            return 'Bar';
        }
    }
    echo "<h1>Bar: ".\Foo\Bar::getBar()."</h1>";
    // outputs 'Bar: Bar'
    $function = '\Foo\Bar::getBar';
    echo "<h1>Bar: ".$function()."</h1>";
    // outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()'
    $function = '\Foo\Bar\getBar';
    echo "<h1>Bar: ".$function()."</h1>";
    // outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()'
}

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

您可以在此处查看输出结果:https: //3v4l.org/iBERh似乎第二种方法适用于 PHP 7 以上,但不适用于 PHP 5.6。