Calling a function in a PHP script from the command line

I have a script that has many different parameterized functions. Is it possible to call any of these functions from the command line and pass arguments to me instead of making it difficult for me to write function calls in a script?

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

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

+5
source share
6 answers

No, you cannot do this directly. You have several options:

  • Put each function in a separate php file and call the php file
  • , php , , .

Update:

:

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

PHP .php arg1 arg2 $argv [1], $argv [2]... .. script.

+3

getopt() CLI.

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
    )

$arguments[a](); foo();, b , arg.

0

100% , , -

PHP .php arg1 arg2 arg3

, , . script $argv, $argv[0] script, $argv[1] "arg1" .. , $_SERVER['argv'].

, getopt

0

You can force the script command line to use your first argument as a function to call, and then the arguments you need to pass to it. Arguments will appear in the variable of the magic array $argv.

// Zero'th "argument" is just the name of your PHP 
$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 need to make things more complicated for security or pass special values ​​of some kind, but this does the basic logic that you describe in the question.

0
source

You can write an option and then pass it to a function, for example myscript.php -function my_function

then in your script call a function like

$argv[1]()
0
source

All Articles