且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP,将参数从命令行传递到PHP脚本

更新时间:2023-02-20 08:46:44

从命令行调用PHP脚本时,可以使用$ argc找出要传递的参数数量,并可以使用$ argv来访问它们.例如,运行以下脚本:

When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:

<?php
    var_dump($argc); //number of arguments passed 
    var_dump($argv); //the arguments passed
?>

像这样:-

php script.php arg1 arg2 arg3

将给出以下输出

int(4)
array(4) {
  [0]=>
  string(21) "d:\Scripts\script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

请参见 $ argv

See $argv and $argc for further details.

要做你想做的事

php script.php arg1=4

您需要将等号上的参数展开:-

You would need to explode the argument on the equals sign:-

list($key, $val) = explode('=', $argv[1]);
var_dump(array($key=>$val));

这样,您可以在等号前面拥有所需的任何内容而不必解析它,只需检查key => value对是否正确即可.但是,这只是浪费,只是指导用户按照正确的顺序传递参数.

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.