php函数参数

Cli*_* C. 4 php arguments function optional-arguments

我不知道我是怎么或在哪里得到这个想法,但出于某种原因我认为这是可能的.显然,经过测试它不起作用,但有没有办法让它工作?我想设置$ value2而不必为$ value1输入任何东西.

function test($value1 = 1, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test($value2 = 3);

// output
Value 1: 3
Value 2: 2
Run Code Online (Sandbox Code Playgroud)

Sta*_*arx 8

它完全不可能以你想要的方式.

只是,

function test($value1 = null, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test(NULL, $value2 = 3);
Run Code Online (Sandbox Code Playgroud)

或者,使用数组作为参数

function test($array) {

if(isset($array['value1'])) echo 'Value 1: '.$array['value1'].'<br />';
if(isset($array['value2'])) echo 'Value 2: '.$array['value2'].'<br />';

}

test(array('value2' => 3));
Run Code Online (Sandbox Code Playgroud)

更新:

我的另一次尝试

function test() {
  $args = func_get_args();
  $count = count($args);
  if($count==1) { test1Arg($args[0]); }
  elseif($count == 2) { test2Arg($args[0],$args[1]); }
  else { //void; }
}

function test1Arg($arg1) {
   //Do something for only one argument
}
function test2Arg($arg1,$arg2) {
   //Do something for two args
}
Run Code Online (Sandbox Code Playgroud)

  • `test(NULL,$ value2 = 3);`导致了不需要的行为,因为`$ value2 =`做了一些与OP想要做的完全不同的事情,并且在读取时会产生误导. (2认同)