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?
F.Y.I: 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
access them as $argv[1], $argv[2]...and so on, in your script.
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]()
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.