PHP中 接收命令行参数

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

转载:http://hi.baidu.com/wuhui/item/5fcc4fc6675d9f22a0b50a02


1.$argv
PHP 的二进制文件(php.exe 文件)及其运行的 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本程序的参数的个数(外壳程序对命令行的字符数有限制,但通常都不会超过该限制)。传递给脚本的参数可在全局变量 $argv 中获取。该数组中下标为零的成员为脚本的名称(当 PHP 代码来自标准输入获直接用 -r 参数以命令行方式运行时,该名称为“-”)。另外,全局变量 $argc 存有 $argv 数组中成员变量的个数(而非传送给脚本程序的参数的个数)。

只要传送给脚本的参数不是以 - 符号开头,就无需过多的注意什么。向脚本传送以 - 开头的参数会导致错误,因为 PHP 会认为应该由它自身来处理这些参数。可以用参数列表分隔符 -- 来解决这个问题。在 PHP 解析完参数后,该符号后所有的参数将会被原样传送给脚本程序。

# 以下命令将不会运行 PHP 代码,而只显示 PHP 命令行模式的使用说明:
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# 以下命令将会把“-h”参数传送给脚本程序,PHP 不会显示命令行模式的使用说明:
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}

除此之外,还有另一个方法将 PHP 用于外壳脚本。可以在写一个脚本,并在第一行以 #!/usr/bin/php 开头,在其后加上以 PHP 开始和结尾标记符包含的正常的 PHP 代码,然后为该文件设置正确的运行属性(例如:chmod +x test)。该方法可以使得该文件能够像外壳脚本或 PERL 脚本一样被直接执行。 #!/usr/bin/php
<?php
var_dump($argv);
?>

假设改文件名为 test 并被放置在当前目录下,可以做如下操作:



$ chmod +x test

$ ./test -h -- foo

array(4) {

  [0]=>

  string(6) "./test"

  [1]=>

  string(2) "-h"

  [2]=>

  string(2) "--"

  [3]=>

  string(3) "foo"

}


正如所看到的,在向该脚本传送以 - 开头的参数时,脚本仍然能够正常运行。

<?php
echo $argc . "\n";
var_dump($argv);
?>



H:\workspace>php test.php arg1 arg2

3

array(3) {

  [0]=>

  string(8) "test.php"

  [1]=>

  string(4) "arg1"

  [2]=>

  string(4) "arg2"

}



2.getopt

getopt

(PHP 4 >= 4.3.0, PHP 5)
getopt -- Gets options from the command line argument list
Description
array getopt ( string options [, array longopts] )

Returns an associative array of option / argument pairs based on the options format specified in options, or FALSE on an error.

On platforms that have the C function getopt_long, long options can be specified with the parameter longopts (as of PHP 4.3.0).
<?php
// parse the command line ($GLOBALS['argv'])
$options = getopt("f:hp:");
?>

The options parameter may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string x recognizes an option -x, and an option string x: recognizes an option and argument -x argument. It does not m

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/gftygff/article/details/83891496