【发布时间】:2010-11-01 17:47:03
【问题描述】:
我想从命令行运行一个 PHP 脚本,但我也想为该脚本设置一个变量。
浏览器版本:script.php?var=3
命令行:php -f script.php(但如何给它包含 3 的变量?)
【问题讨论】:
标签: php command-line
我想从命令行运行一个 PHP 脚本,但我也想为该脚本设置一个变量。
浏览器版本:script.php?var=3
命令行:php -f script.php(但如何给它包含 3 的变量?)
【问题讨论】:
标签: php command-line
除了 argv(正如 Ionut 提到的),您还可以使用环境变量:
例如:
var = 3 php -f test.php
在test.php中:
$var = getenv("var");
【讨论】:
许多解决方案将参数按照它们的顺序放入变量中。例如,
myfile.php 5 7
将 5 放入第一个变量,将 7 放入下一个变量。
我想要命名参数:
myfile.php a=1 x=8
以便我可以将它们用作 PHP 代码中的变量名。
Ionuț G. Stan 提供的链接 http://www.php.net/manual/en/features.commandline.php
给了我答案。
sep16 at psu dot edu:
您可以使用 parse_str() 函数轻松地将命令行参数解析到 $_GET 变量中。
<?php
parse_str(implode('&', array_slice($argv, 1)), $_GET);
?>
它的行为与您对 cgi-php 的期望完全一样。
$ php -f somefile.php a=1 b[]=2 b[]=3
这会将 $_GET['a'] 设置为 '1' 并将 $_GET['b'] 设置为 array('2', '3')。
【讨论】:
parse_str函数之前使用if (PHP_SAPI === 'cli'),因为在web上使用时不会覆盖$_GET。
除了使用Ionut G. Stan 指示的argc 和argv,您还可以使用PEAR 模块Console_Getopt,它可以解析出unix 样式的命令行选项。请参阅this article 了解更多信息。
另外,Zend 框架中的 Zend_Console_Getopt 类也有类似的功能。
【讨论】:
脚本:
<?php
// number of arguments passed to the script
var_dump($argc);
// the arguments as an array. first argument is always the script name
var_dump($argv);
命令:
$ php -f test.php foo bar baz
int(4)
array(4) {
[0]=>
string(8) "test.php"
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
}
【讨论】: