简体   繁体   中英

Calling a function in a PHP script from the command line

I have a script that has a bunch of different parameterized functions. Is it possible to call any of these functions from the command line and pass in the arguments instead of me having to hard code the function calls in the script?

FYI: I do know how to execute a simple PHP script from the command line

doesn't quite call the function, remember script.php has around 5 different functions and I am looking to call only 1, is that possible

No, you cannot do that directly. You have a few options:

  • Put every function in a separate php file and call the php file
  • use the first argument passed to the php file as the function name, and write a few lines of code to select the correct function.

Update:

Here is a example of using the first passed parameter as a function call:

if(function_exists( $argv[1] ))
  call_user_func_array($argv[1], $argv);

php script.php arg1 arg2在你的脚本中以$ argv [1],$ argv [2] ......等方式访问它们。

getopt() takes CLI parameters.

php /path/to/myscript.php -a foo -b bar -c baz

$arguments = getopt("a:b:c:");

print_r($arguments);

    Array
    (
        [a] => foo
        [b] => bar
        [c] => baz
    )

Make it a function $arguments[a](); to call foo(); you can pass in b also if you have a function arg.

Not 100% sure what you're asking, but the execution would be something like

php script.php arg1 arg2 arg3

You seem to already know that. The method for accessing those arguments within the script itself would be to use the variable $argv , so $argv[0] would be the script, $argv[1] would be "arg1" , etc. If that doesn't work, then use $_SERVER['argv'] .

As for options, you can parse them with getopt

You could make the command-line script use its first argument as the function to call, and subsequently the arguments to pass to it. The arguments will appear in the magic array variable $argv .

// Zero'th "argument" is just the name of your PHP script
$name_of_php_script = array_unshift($argv);
// Next argument will be your callback
$callback = array_unshift($argv);
// Remaining arguments are your parameters
call_user_func_array($callback, $argv);

Obviously, you may want to make things more complicated for security, or to pass in special values of some sort, but this does the basic logic you describe in the question.

You can write an option, then pass the function to that eg myscript.php -function my_function

then in your script call the function like

$argv[1]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM