我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:

function foo ()
{
    //code here
}

function bar ()
{
    //code here
}

$functionName = "foo";
// I need to call the function based on what is $functionName

当前回答

如前所述,有几种方法可以实现这一点,最安全的方法可能是call_user_func(),如果必须,也可以使用$function_name()。可以这样使用这两种方法传递参数

$function_name = 'foobar';

$function_name(arg1, arg2);

call_user_func_array($function_name, array(arg1, arg2));

如果你调用的函数属于一个对象,你仍然可以使用它们中的任何一个

$object->$function_name(arg1, arg2);

call_user_func_array(array($object, $function_name), array(arg1, arg2));

然而,如果您打算使用$function_name()方法,如果名称是动态的,那么测试函数是否存在可能是个好主意

if(method_exists($object, $function_name))
{
    $object->$function_name(arg1, arg2);
}

其他回答

我想到的一种非常规方法是,除非你是通过一些超级超级自主的AI来生成整个代码,否则你想要“动态”调用的函数很有可能已经在你的代码库中定义了。所以为什么不只是检查字符串,并做臭名昭著的ifelse舞蹈来召唤…你明白我的意思了。

eg.

if($functionName == 'foo'){
  foo();
} else if($functionName == 'bar'){
  bar();
}

如果你不喜欢ifelse梯子的无味味道,甚至可以使用开关盒。

我知道在某些情况下,“动态调用函数”是绝对必要的(就像一些修改自身的递归逻辑)。但是大多数日常琐碎的用例都可以被避开。

它从应用程序中清除了许多不确定性,同时如果字符串不匹配任何可用函数的定义,则为您提供了执行回退函数的机会。恕我直言。

如果有人被谷歌带到这里,因为他们试图在一个类中使用一个方法的变量,下面是一个实际工作的代码示例。以上这些方法都不适用于我的情况。关键的区别在于$c = & new…&$c在call_user_func中传递。

我的具体情况是当实现某人的代码必须与颜色和两个成员方法点亮()和暗()从csscolor.php类。不管出于什么原因,我希望有相同的代码能够调用变亮或变暗,而不是用逻辑选择它。这可能是我固执地不使用if-else或更改调用此方法的代码的结果。

$lightdark="lighten"; // or optionally can be darken
$color="fcc";   // a hex color
$percent=0.15;  
include_once("csscolor.php");
$c = & new CSS_Color($color);
$rtn=call_user_func( array(&$c,$lightdark),$color,$percent);

注意,尝试使用$c->{…不管用。通过阅读php.net页面底部call_user_func上的读者提供的内容,我能够将上述内容拼凑在一起。另外,请注意$params作为数组对我不起作用:

// This doesn't work:
$params=Array($color,$percent);
$rtn=call_user_func( array(&$c,$lightdark),$params);

上述尝试将给出关于该方法期望第二个参数(percent)的警告。

我从这个问题和答案中学到了什么。感谢所有!

假设我有这些变量和函数:

$functionName1 = "sayHello";
$functionName2 = "sayHelloTo";
$functionName3 = "saySomethingTo";

$friend = "John";
$datas = array(
    "something"=>"how are you?",
    "to"=>"Sarah"
);

function sayHello()
{
echo "Hello!";
}

function sayHelloTo($to)
{
echo "Dear $to, hello!";
}

function saySomethingTo($something, $to)
{
echo "Dear $to, $something";
}

To call function without arguments // Calling sayHello() call_user_func($functionName1); Hello! To call function with 1 argument // Calling sayHelloTo("John") call_user_func($functionName2, $friend); Dear John, hello! To call function with 1 or more arguments This will be useful if you are dynamically calling your functions and each function have different number of arguments. This is my case that I have been looking for (and solved). call_user_func_array is the key // You can add your arguments // 1. statically by hard-code, $arguments[0] = "how are you?"; // my $something $arguments[1] = "Sarah"; // my $to // 2. OR dynamically using foreach $arguments = NULL; foreach($datas as $data) { $arguments[] = $data; } // Calling saySomethingTo("how are you?", "Sarah") call_user_func_array($functionName3, $arguments); Dear Sarah, how are you?

耶再见!

我不知道你为什么要用它,听起来对我来说一点都不好,但如果只有少量的函数,你可以使用if/elseif结构。 我不知道是否有直接的解决办法。

类似的 $foo = "bar"; $test = "foo"; echo $ $测试;

应该返回酒吧,你可以尝试,但我不认为这将工作的功能

考虑到这里给出的一些很好的答案,有时你需要精确。 为例。

如果一个函数有返回值,例如(boolean,array,string,int,float e.t.c)。 如果函数没有返回值,则检查 如果函数存在

让我们来看看这些答案的可信度。

Class Cars{
        function carMake(){
        return 'Toyota';
        }
        function carMakeYear(){
        return 2020;
        }
        function estimatedPriceInDollar{
        return 1500.89;
        }
        function colorList(){
        return array("Black","Gold","Silver","Blue");
        }
        function carUsage(){
        return array("Private","Commercial","Government");
        }
    function getCar(){
    echo "Toyota Venza 2020 model private estimated price is 1500 USD";
    }
 }

我们想要检查方法是否存在并动态调用它。

$method = "color List";
        $class = new Cars();
        //If the function have return value;
        $arrayColor = method_exists($class, str_replace(' ', "", $method)) ? call_user_func(array($this, $obj)) : [];
        //If the function have no return value e.g echo,die,print e.t.c
     $method = "get Car";
        if(method_exists($class, str_replace(' ', "", $method))){
        call_user_func(array($class, $method))
        }

谢谢