4

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.

Online
  • 71
  • 1
  • 8

2 Answers2

0

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

    }
  • This will override __any meaningful__ value other than `1` with the default value. Use `if ($sent_email === null)` as the condition to replace only (non meaningful) `null` values. – Philipp Maurer Sep 21 '18 at 12:16
-1

In php you cannot declare more than 1 parameter with default value in your function. Php could not know wich param you do not give if you have multiple default value...

In your case, you give the param, with null value. 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 ;)

M.Be
  • 312
  • 1
  • 4
  • 14
  • 1
    "In php you cannot declare more than 1 parameter with default value in your function" Sure you can. – PeeHaa Sep 28 '16 at 12:46