参数处理

参数以类似于大多数 C 风格语言的方式传递给程序。$argc 是一个整数,包含包含程序名称的参数个数,$argv 是一个包含程序参数的数组。$argv 的第一个元素是程序的名称。

#!/usr/bin/php

printf("You called the program %s with %d arguments\n", $argv[0], $argc - 1);
unset($argv[0]);
foreach ($argv as $i => $arg) {
    printf("Argument %d is %s\n", $i, $arg);
}

使用 php example.php foo bar 调用上述应用程序(其中 example.php 包含上面的代码)将导致以下输出:

你用 2 个参数调用了程序 example.php。
参数 1 是 foo
参数 2 是 bar

请注意,$argc$argv 是全局变量,而不是超全局变量。如果函数需要 global 关键字,则必须使用 global 关键字将它们导入本地范围。

此示例显示了在使用诸如 ""\之类的转义时如何对参数进行分组。

示例脚本

var_dump($argc, $argv);

命令行

$ php argc.argv.php --this-is-an-option three\ words\ together or "in one quote"     but\ multiple\ spaces\ counted\ as\ one
int(6)
array(6) {
  [0]=>
  string(13) "argc.argv.php"
  [1]=>
  string(19) "--this-is-an-option"
  [2]=>
  string(20) "three words together"
  [3]=>
  string(2) "or"
  [4]=>
  string(12) "in one quote"
  [5]=>
  string(34) "but multiple spaces counted as one"
}

如果使用 -r 运行 PHP 脚本:

$ php -r 'var_dump($argv);'
array(1) {
  [0]=>
  string(1) "-"
}

或者通过管道传输到 php 的 STDIN:

$ echo '<?php var_dump($argv);' | php
array(1) {
  [0]=>
  string(1) "-"
}