PHP 参数处理

示例

参数以与大多数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);
}

使用(包含上面的代码)调用上述应用程序将导致以下输出:phpexample.phpfoo barexample.php

您example.php使用2个参数调用了该程序
参数1是foo
参数2是bar

请注意,$argc和$argv是全局变量,而不是超全局变量。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) "-"
}

或通过管道传递到STDIN的代码php:

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