使用默认值跳过/不设置 PHP 函数中的参数

Skipping / not setting parameters in PHP functions with default values

假设我有

function test($a, $b, $c=3, $d=4) {
  // ...
}
test(1, 2);          // $c == 3, $d == 4
test(1, 2,     , 9); // syntax error
test(1, 2, null, 9); // $c == null

我希望能够将 $d 设置为 9,但将 $c 的默认值保留为 3。
当然,如果我知道默认值,我可以设置它。但这是一个糟糕的解决方案,因为首先我必须知道它,其次如果它在函数声明中被更改,我也必须在我的代码中更改它。
另一种解决方案是交换参数顺序,但我必须处理的代码相当复杂,所以我想知道 PHP 中是否有“标准”解决方案来传递一个参数让解释器使用默认值(如果存在)。

据我所知,我们需要为此制定逻辑

function test($a, $b, $c=null, $d=null) {
    if (null === $c) { $c = 3; }
    if (null === $d) { $d = 4; }
    echo $a." ".$b." ".$c." ".$d;
}
test('',1,null,5);

输出:1 3 5

在 php 8.0.0 中,您可以指定参数。

<?php
function test($a, $b, $c=3, $d=4) {
  var_dump( $c );//int(3)
}

test(1, 2, d:9); // $c == 3
?>

Named Arguments