Php 将默认参数发送为null并使用函数中设置的默认值

Php 将默认参数发送为null并使用函数中设置的默认值,php,function,Php,Function,我的功能如下 function test($username, $is_active=1, $sent_email=1, $sent_sms=1) { echo $sent_email; // It should print default ie 1 } 调用函数: test($username, 1, null, 1); 如果需要在函数中使用默认值,如何调用函数$已发送的电子邮件应为1。无法更改参数的顺序 在php中,不能在函数中声明多个具有默认值的参数。 如果您有多个默认值

我的功能如下

function test($username, $is_active=1, $sent_email=1, $sent_sms=1) {

  echo $sent_email;  // It should print default ie 1

}
调用函数:

  test($username, 1, null, 1);

如果需要在函数中使用默认值,如何调用函数$已发送的电子邮件应为1。无法更改参数的顺序

在php中,不能在函数中声明多个具有默认值的参数。 如果您有多个默认值,Php无法知道您未提供的参数

在您的例子中,您使用null值指定参数。那太不一样了!因此,您可以使用以下选项:

function test($username, $is_active, $sent_email, $sent_sms) {
    $username = ($username != null) ? $username : 1;
    $is_active = ($is_active != null) ? $is_active : 1;
    $sent_email = ($sent_email != null) ? $sent_email : 1;

  echo $sent_email;  // It should print default ie 1

}

因此,如果给定null,函数将使用“1”值,如果不是null,则使用作为参数传递的值;)

启动值参数时:
 function makecoffee($type = "cappuccino")
    {
        return "Making a cup of $type.\n";
    }
    echo makecoffee();
    echo makecoffee(null);
    echo makecoffee("espresso");
    ?>
上述示例将输出:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

要满足您要检查的内容,请满足以下条件:

function test($username, $is_active=1, $sent_email=1, $sent_sms=1) {

    if($sent_email!=1)
        $sent_email=1;
      echo $sent_email;  // It should print default ie 1

    }

你的函数做得太多了,现在你知道这是个问题的原因了。向它传递一个参数数组
函数测试(数组$params)
…并阅读“在php中,你不能在函数中声明超过1个默认值的参数”。这将用默认值覆盖除
1
之外的任何有意义的值。使用
if($sent\u email===null)
作为仅替换(无意义的)
null
值的条件。