How to call a function from a string stored in a variable?

后端 未结 16 2433
予麋鹿
予麋鹿 2020-11-22 10:16

I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:

function foo ()
{
  //code here
}

function bar ()
{
          


        
16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 11:01

    What I learnt from this question and the answers. Thanks all!

    Let say I have these variables and functions:

    $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";
    }
    
    1. To call function without arguments

      // Calling sayHello()
      call_user_func($functionName1); 
      

      Hello!

    2. To call function with 1 argument

      // Calling sayHelloTo("John")
      call_user_func($functionName2, $friend);
      

      Dear John, hello!

    3. 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?

    Yay bye!

提交回复
热议问题