php cli模式下获取参数的方法

php在cli模式下接收参数有两种方法

1.使用argv数组
2.使用getopt方法


1.使用argv数组

例如:须要执行一个php,并传递三个参数(type=news, is_hot=1, limit=5)php

建立test.php数组

<?php
print_r($argv);
?>


在命令行执行函数

php test.php news 1 5

输出:spa

Array
(
[0] => test.php
[1] => news
[2] => 1
[3] => 5
)

 



能够看到argv[0]为当前执行的php文件名称,而argv[1]~argv[3]则是传递的参数的值
argv[1]等于type的值
argv[2]等于is_hot的值
argv[3]等于limit的值
这样能够根据argv数组来获取传递的参数进行后续的处理操做。命令行

缺点:
使用argv数组,能够按顺序获取传递的参数。但获取后,须要作一个对应处理,上例中须要把argv[1]对应type参数,argv[2]对应is_hot参数,argv[3]对应limit参数。而若是在传递的过程当中,参数顺序写错,则会致使程序出错。code

例如:blog

<?php
$param = array();
$param['type'] = $argv[1];
$param['is_hot'] = $argv[2];
$param['limit'] = $argv[3];

print_r($param);

 

执行字符串

php test.php news 1 5

输出:

Array
(
    [type] => news
    [is_hot] => 1
    [limit] => 5
)

 

而传递顺序不一样,获取到的参数数值会不一样,致使后续程序出错get

执行string

php test.php 1 5 news

输出:

Array
(
    [type] => 1
    [is_hot] => 5
    [limit] => news
)

 


所以在使用argv数组传递参数时,须要注意参数传递的顺序。


2.使用getopt方法


getopt 从命令行参数列表中获取选项

array getopt ( string $options [, array $longopts ] )


参数:
options
该字符串中的每一个字符会被当作选项字符,匹配传入脚本的选项以单个连字符(-)开头。 好比,一个选项字符串 “x” 识别了一个选项 -x。 只容许 a-z、A-Z 和 0-9。

longopts
选项数组。此数组中的每一个元素会被做为选项字符串,匹配了以两个连字符(–)传入到脚本的选项。 例如,长选项元素 “opt” 识别了一个选项 –opt。

options 可能包含了如下元素:
单独的字符(不接受值)
后面跟随冒号的字符(此选项须要值)
后面跟随两个冒号的字符(此选项的值可选)
选项的值是字符串后的第一个参数。它不介意值以前是否有空格。

options 和 longopts 的格式几乎是同样的,惟一的不一样之处是 longopts 须要是选项的数组(每一个元素为一个选项),而 options 须要一个字符串(每一个字符是个选项)。
传值的分隔符可使用空格或=。
可选项的值不接受空格做为分隔符,只能使用=做为分隔符。

返回值
此函数会返回选项/参数对,失败时返回 FALSE。
选项的解析会终止于找到的第一个非选项,以后的任何东西都会被丢弃。


1.使用options实例
a,b,c 为须要值
d 为可选值
e 为不接受值

<?php
$param = getopt('a:b:c:d::e');
print_r($param);


执行

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

输出:

Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 
)

 

2.使用longopts实例
type,is_hot 为须要值
limit 为可选值
expire 为不接受值

<?php
$longopt = array(
'type:',
'is_hot:',
'limit::',
'expire'
);
$param = getopt('', $longopt);
print_r($param);

 

执行

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

输出:

Array
(
[type] => news
[is_hot] => 1
[limit] => 10
[expire] => 
)

 

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

<?php
$longopt = array(
'type:',
'is_hot:',
'limit::',
'expire'
);
$param = getopt('', $longopt);
print_r($param);


执行

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

输出:

Array
(
[type] => news
)

 


由于is_hots不是选项值(定义的是is_hot),因此从这里开始以后的参数,都被丢弃。

总结:使用argv数组传参数,方法简单,实现方便。参数的顺序不能错,参数获取后须要作对应处理。使用getopt方法,可以使用参数名,参数顺序可随意,比较规范。(建议使用)

相关文章
相关标签/搜索