如何获取可选参数的默认值

Kat*_*tai 5 php function optional-parameters

可能这是PHP的限制,但是有可能以某种方式调用函数 - 并强制执行可选参数的'default'值 - 即使在函数调用中,给出了可选参数(和== null)?

也许更容易表明我的意思:

<?php
    function funcWithOptParam($param1, $param2 = 'optional') {
        print_r('param2: ' . $param2);
    }

    funcWithOptParam('something'); // this is the behaviour I want to reproduce

    // this will result in 'param2: optional'

    funcWithOptParam('something', null); // i want $param2 to be 'optional', not null

    // this will result in 'param2: ' instead of 'param2: optional'
?>
Run Code Online (Sandbox Code Playgroud)

现在,最简单的答案是"不要写null" - 但在我的特殊情况下,我得到array一个function调用的参数,只能这样做:

<?php
    funcWithOptParam($param[0], $param[1]);
?>
Run Code Online (Sandbox Code Playgroud)

因此,即使$param[1]null,null也会覆盖可选参数的默认值

我只看到一个解决方案 - 跳过可选参数,并按以下方式执行:

<?php
    function funcWithOptParam($something, $notOptional) {
         if($notOptional === null) {
              $notOptional = 'defaultvalue';
         }

         ...
    }
?>
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有另一种解决方案.nullPHP中有"真正的" 价值吗?这真的转化为"什么都没有"?有点像undefinedjs吗?

小智 3

为什么不将整个数组作为函数参数传递?你只需这样称呼它:

funcWithOptParams($params);
Run Code Online (Sandbox Code Playgroud)

并像这样处理它:

function funcWithOptParams($params) {
     if(!isset($params[1])) {
          $params[1] = 'defaultvalue';
     }

     ...
}
Run Code Online (Sandbox Code Playgroud)

这种方法使您可以仅传递您想要指定的参数,并在您不想指定的参数中使用默认值。作为奖励,您不必担心参数的顺序。