简体   繁体   English

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

[英]Sending default parameter as null and use default value set in function

I have function as below. 我的功能如下。

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

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

}

Call to function : 呼吁功能:

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

How to call function if need to use default value in function. 如果需要在函数中使用默认值,如何调用函数。 $sent_email should be 1. Can not change sequence of parameter. $ sent_email应为1.不能更改参数序列。

When you start the value parameters happens: 当您启动值参数时:

 function makecoffee($type = "cappuccino")
    {
        return "Making a cup of $type.\n";
    }
    echo makecoffee();
    echo makecoffee(null);
    echo makecoffee("espresso");
    ?>

The above example will output: 上面的例子将输出:

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

To fulfill what you want to check with conditions as follows: 要满足您要检查的条件,条件如下:

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

    }

In php you cannot declare more than 1 parameter with default value in your function. 在php中,您不能在函数中使用默认值声明多于1个参数。 Php could not know wich param you do not give if you have multiple default value... 如果你有多个默认值,Php无法知道你不给的param ...

In your case, you give the param, with null value. 在您的情况下,您给param,值为null。 That's a lot different ! 那有很多不同! So, you can use the following : 因此,您可以使用以下内容:

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

}

as it, if you give null, your function will use "1" value, and if not null, the value you pass as parameter ;) 因为它,如果你给null,你的函数将使用“1”值,如果不为null,你传递的值作为参数;)

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

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