我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
当前回答
如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:
$this->{$variable}();
其他回答
使用存储在变量中的名称安全地调用函数的最简单方法是,
//I want to call method deploy that is stored in functionname
$functionname = 'deploy';
$retVal = {$functionname}('parameters');
我使用如下方法在Laravel中动态创建迁移表,
foreach(App\Test::$columns as $name => $column){
$table->{$column[0]}($name);
}
$functionName()或call_user_func($functionName)
考虑到这里给出的一些很好的答案,有时你需要精确。 为例。
如果一个函数有返回值,例如(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))
}
谢谢
补充@Chris K的回答,如果你想调用一个对象的方法,你可以在闭包的帮助下使用一个变量来调用它:
function get_method($object, $method){
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
class test{
function echo_this($text){
echo $text;
}
}
$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello'); //Output is "Hello"
我在这里举了另一个例子
我不知道你为什么要用它,听起来对我来说一点都不好,但如果只有少量的函数,你可以使用if/elseif结构。 我不知道是否有直接的解决办法。
类似的 $foo = "bar"; $test = "foo"; echo $ $测试;
应该返回酒吧,你可以尝试,但我不认为这将工作的功能