Users who are accustomed to the Linux system should know that many of the Linux commands support options and value inputs, such as
rm -f hello.txt
、
ls -al
、
netstat -tnl
And so on, how do you enable the input of options and values when PHP scripts are executed in CLI mode? There are two ways of doing this:
Use the getopt () function
Suppose you now need a PHP script that supports the input of three options:
-A: Value input not accepted
-B: Accept value input
-C: Accepts value input, and the value is optional
Based on the above requirements, you can write PHP scripts:
functionmain($args) { var_dump($args);}/* * 选项字符后面不带冒号,表示该选项不支持值输入 * 选项字符后面带一个冒号,表示该选项支持值输入 * 选项字符后面带两个冒号,表示该选项支持值输入,且值可选 */$args = getopt('ab:c::');main($args);
Then use the command to execute the script, here in Linux for example, and assume that the foot name is test.php, note. The-f option is not required between/php and test.php:
./php test.php -a -b=valueOfB -c=valueOfC
Output:
Because the value of the C option is optional, let's try what happens if the C option does not pass a value:
You can see that the option with no value corresponds to the array value is False
One thing to note here is that the options and values are connected using the equals sign "=", or you can omit the equals number, and you can not use spaces to split options and values, for example -b valueOfB
, otherwise you might not get a value.
getopt()
Also supports options that start with two bars, for example --a
, the second parameter that details can refer to getopt()
$longopts
Using the $ARGV variable
If you simply want to pass some values to the script, you can use $argv
this variable, for more information about this variable, see: http://php.net/manual/zh/reserved.variables.argv.php
PHP Script:
var_dump($argv);
Execute command./php test.php valueOfA valueOfB valueOfC
Output:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The above describes how to let PHP script in the CLI mode to accept the input of options and values, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.