从命令行运行带有变量的php脚本

Hin*_*wen 21 php command-line

我想从命令行运行PHP脚本,但我也想为该脚本设置一个变量.

浏览器版本: script.php?var=3

命令行:( php -f script.php 但是如何给它包含3的变量?)

Ion*_*tan 36

脚本:

<?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);
Run Code Online (Sandbox Code Playgroud)

命令:

$ 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"
}
Run Code Online (Sandbox Code Playgroud)

另外,请看一下从命令行使用PHP.


Mat*_*hen 7

除了argv(如Ionut所提到的),您可以使用环境变量:

例如:

var = 3 php -f test.php
Run Code Online (Sandbox Code Playgroud)

在test.php中:

$var = getenv("var");
Run Code Online (Sandbox Code Playgroud)


Vol*_*erK 6

如果你想保持命名参数几乎像var = 3&foo = bar(而不是$ argv提供的位置参数),getopt()可以帮助你.