Call a PHP function from the command line

后端 未结 6 2070
野性不改
野性不改 2020-12-29 19:13

I have a file called address.php with a few functions in it. I want to call a specific function in that file from the command line. How?

The name of the function is

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 19:42

    To extend on Samer Ata and Simon Rodan's answers, you can use the following to be able to execute any function with any amount of arguments:

    if(isset($argv[1]) && function_exists($argv[1])) {
      $parameters = array_slice($argv, 2);
      call_user_func($argv[1], ...$parameters);
    }
    

    This is done by removing the script and function name from $argv and then using the spread operator (...) to interpret each element in the array as an argument to call_user_func.

    The operator is supported from PHP 5.6 onward (and 5.5 can do some of the things using functions). You can read more about it in the official PHP documentation. For completeness, this is also known as argument unpacking.

提交回复
热议问题