Home >Backend Development >PHP Tutorial >How to make a PHP script accept input of options and values when executed in cli mode
Users who are used to Linux systems should know that many commands in Linux support the input of options and values, such as rm -f hello.txt
, ls -al
, netstat -tnl
, etc. So what? How to make PHP scripts also support the input of options and values when executed in cli mode? There are two methods:
Suppose now you need a PHP script to support the input of three options:
-a: Do not accept value input
-b: accept value input
-c: Accept value input, and the value is optional
According to the above requirements, you can write a PHP script:
<code><span><span>function</span><span>main</span><span>(<span>$args</span>)</span> {</span> var_dump(<span>$args</span>); } <span>/* * 选项字符后面不带冒号,表示该选项不支持值输入 * 选项字符后面带一个冒号,表示该选项支持值输入 * 选项字符后面带两个冒号,表示该选项支持值输入,且值可选 */</span><span>$args</span> = getopt(<span>'ab:c::'</span>); main(<span>$args</span>);</code>
Then use the command to execute the script. Here, Linux is used as an example, and assuming the script is named test.php, note. No need for -f option between /php and test.php: ./php test.php -a -b=valueOfB -c=valueOfC
Output:
because the value of c option is optional , let’s try what happens if option c does not pass a value:
As you can see, the array value corresponding to the option without a value is false
One thing to note here is that the options and values are connected using the equal sign "=", or you can omit the equal sign, and you cannot use spaces. to separate options and values, such as -b valueOfB
, otherwise the value may not be obtained.
getopt()
also supports options starting with two dashes, such as --a
. For details, please refer to the second parameter $longopts of getopt()
if only If you simply want to pass some values to the script, you can use the variable $argv
. For detailed information about this variable, please refer to: http://php.net/manual/zh/reserved.variables.argv.php
PHP script:
<code>var_dump(<span>$argv</span>);</code>
Execute command./php test.php valueOfA valueOfB valueOfC
Output:
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
The above introduces how to make the PHP script accept input of options and values when executed in cli mode, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.