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

标签 php function optional-parameters

可能这是 PHP 的限制,但是否有可能以某种方式调用函数 - 并强制执行可选参数的“默认”值 - 即使在函数调用中,给出了可选参数(并且 == 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'
?>

现在,最简单的答案是“然后不要写 null”——但在我的特殊情况下,我得到一个参数 array 用于 function 调用,并且只能这样做:

<?php
    funcWithOptParam($param[0], $param[1]);
?>

所以即使$param[1]nullnull也会覆盖可选参数的默认值

我只看到一个解决方案——跳过可选参数,然后这样做:

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

         ...
    }
?>

但我想知道是否有其他解决方案。 PHP 中是否存在“真实的”null 值?这真的转化为“无”?像 js 中的 undefined 之类的东西?

最佳答案

为什么不将整个数组作为函数参数传递? 您只需这样调用它:

funcWithOptParams($params);

然后这样处理:

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

     ...
}

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

关于php - 如何获取可选参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13208257/

相关文章:

c# - 可选的非系统类型参数

SQL Server : Optional variable in a stored procedure

php - CakePHP:添加 DISTINCT 以查找导致关联被省略

php - 按一个字段从表组中获取所有值

php - Laravel 4 Form::open 设置 Action

bash - 如何使函数对 bash 脚本可见?

c - 试图理解 C 中的函数指针

php - 从 Magento sitemap.xml 生成中排除某些产品

c++ - 通过引用传递指针是执行此操作的正确方法吗?

c - C 是否支持可选的空参数?