【问题标题】:How to call PHP function from string stored in a Variable with arguments [duplicate]如何从存储在带有参数的变量中的字符串中调用PHP函数[重复]
【发布时间】:2015-05-20 20:42:50
【问题描述】:

我发现了来自here 的问题。但我需要用参数调用函数名。 我需要能够调用一个函数,但是函数名存储在一个变量中,这可能吗?例如:

function foo ($argument)
{
  //code here
}

function bar ($argument)
{
  //code here
}

$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName

任何帮助将不胜感激。

【问题讨论】:

    标签: php


    【解决方案1】:

    哇,没想到拥有 4 枚金牌的用户会提出这样的问题。你的代码已经可以工作了

    <?php
    
    function foo ($argument)
    {
      echo $argument;
    }
    
    function bar ($argument)
    {
      //code here
    }
    
    $functionName = "foo";
    $argument="Joke";
    $functionName($argument); // works already, might as well have tried :)
    
    ?>
    

    输出

    笑话

    Fiddle

    现在谈一点理论,这些函数称为 Variable Functions

    PHP 支持变量函数的概念。这意味着如果一个变量名附加了括号,PHP 将寻找一个与变量求值结果相同的函数,并尝试执行它。除其他外,这可用于实现回调、函数表等。

    【讨论】:

    • 我需要调用像$this-&gt;function_name这样的函数我该怎么做?
    • 这也可以,只需稍作修改。 $this-&gt;$functionName();
    • 对不起!问愚蠢的问题,但这对我的项目来说很紧急。无论如何它工作正常。谢谢
    • 这个问题本身并不愚蠢,它是一个好问题。但真正不那么酷的是你已经编写了工作代码,而不是尝试它,而是继续并要求其他人运行它:)
    【解决方案2】:

    如果你想用参数动态调用一个函数,那么你可以这样尝试:

    function foo ($argument)
    {
      //code here
    }
    
    call_user_func('foo', "argument"); // php library funtion
    

    希望对你有帮助。

    【讨论】:

    • 我需要调用像$this-&gt;function_name 这样的函数,我该怎么做?
    【解决方案3】:

    你可以使用php函数call_user_func

    function foo($argument)
    {
        echo $argument;
    }
    
    $functionName = "foo";
    $argument = "bar";
    call_user_func($functionName, $argument);
    

    如果你在上课,可以使用call_user_func_array:

    //pass as first parameter an array with the object, in this case the class itself ($this) and the function name
    call_user_func_array(array($this, $functionName), array($argument1, $argument2));
    

    【讨论】:

    • 我需要调用像$this-&gt;function_name 这样的函数我该怎么做?
    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 2017-07-02
    • 2011-04-27
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多