折雨的天空
PHP在CLI模式下接收参数的几种方式
2023-2-17 我好笨


1 argv 方式




PHP test.PHP news 1 5



输出:




//变量仅在 register_argc_argv 打开时可用。
print_r($argc); //CLI下获取参数的数目,最小值为1
print_r($argv); //CLI下传递给脚本的参数数组,第一个参数总是当前脚本的文件名,因此 $argv[0] 就是脚本文件名
//结果
Array
(
[0] => test.PHP
[1] => news
[2] => 1
[3] => 5
)



2 getopt 方式









PHP test.PHP -a 1 -b 2 -c 3 -d=4 -e 5



输出:





$param = getopt('a:b:c:d::e');
print_r($param);
//结果
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] =>
)

3 longopts 方式




PHP test.PHP --type news --is_hot 1 --limit=10 --expire=100



输出:




$longopt = array(
'type:',
'is_hot:',
'limit::',
'expire'
);
$param = getopt('', $longopt);
print_r($param);
//结果
Array
(
[type] => news
[is_hot] => 1
[limit] => 10
[expire] =>
)




注意这种



找到第一非选项,后面忽略实例


PHP test.PHP --type news --is_hots 1 --limit=10 --expire=100





输出:




$longopt = array(
'type:',
'is_hot:',
'limit::',
'expire'
);
$param = getopt('', $longopt);
print_r($param);
//结果
Array
(
[type] => news
)
//因为is_hots不是选项值(定义的是is_hot),所以从这里开始之后的参数,都被丢弃






发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容