: This article mainly introduces how to make PHP scripts accept input of options and values when executed in cli mode. if you are interested in PHP tutorials, refer to it. Users familiar with Linux should know that many Linux commands support input of options and values, such
rm -f hello.txt
,
ls -al
,
netstat -tnl
So, how can I make PHP scripts support input of options and values during execution in cli mode? There are two methods:
Use the getopt () function
Assume that a PHP script is required to support three input options:
-A: value input is not accepted.
-B: accept value input
-C: accept value input, and this value is optional.
Based on the above requirements, you can write a PHP script:
Functionmain ($ args) {var_dump ($ args);}/** the option character is not followed by a colon, indicating that the option does not support value input *. the option character is followed by a colon, indicates that this option supports value input. * The option character is followed by two colons, indicating that this option supports value input. optional values include */$ args = getopt ('AB: c ::'); main ($ args );
Run the following command to execute the script: Linux is used as an example. assume that the script is named test. php. Note that the-f option is not required between./php and test. php:
./php test.php -a -b=valueOfB -c=valueOfC
Output:
Because the value of Option c is optional, let's try out what will happen if option c does not pass the value:
We can see that the array value corresponding to the option with no value is false.
Note that an equal sign (=) is used to connect options and values, or an equal sign (=) is omitted. you cannot use spaces to separate options and values. for example-b valueOfB
Otherwise, the value may not be obtained.
getopt()
It also supports options starting with two horizontal bars, such--a
For more information, seegetopt()
$ Longopts
Use the $ argv variable
If you just 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 Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above describes how to make PHP scripts input options and values acceptable for execution in cli mode, including some content, and hope to help those who are interested in PHP tutorials.