繁体   English   中英

在 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 中是否有“标准”解决方案,传递一个让解释器使用默认值的参数存在时的价值。

在 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
?>

命名参数

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM