简体   繁体   中英

Why do people set default parameters in PHP functions?

Example:

function example($x = "")
{
    Do something
}

Isn't $x empty by default already? Why set it explicitly?

Isn't $x empty by default already?

If no default is specified, $x is not an empty string by default, but an undefined variable. There is a difference between "" and NULL or undefined.
However, setting the default allows you to omit the parameter when calling the function, without it throwing a warning.

<?php
function test1($x = "DEFAULT") {
    echo $x;
}
function test2($x) {
    echo $x;
}

// Call each without the parameter $x:    
test1();
// DEFAULT

test2();
// Output:
PHP Warning:  Missing argument 1 for test2(), called in /home/mjb/test.php on line 10 and defined in /home/user/test.php on line 5
PHP Notice:  Undefined variable: x in /home/user/test.php on line 6

The main reason is that setting a default on the declaration makes the argument optional:

$a = example();
$b = example(5);

One reason is so when you reuse the function you dont have to explicitly set the variable. This happens a lot when a default is set to true or false. That way a function can seem to be overloaded like you can do in other oop languages. If that variable didn't contain a default value, you'd always have to set that value or your function would throw an error, however, by setting the variable to a default value you wouldn't have to necessarily set the value of the variable. Hope that helps some :)

Once of the reasons I use default values is so that I do not have to declare the variable when calling function ie:

function something(debug=false){
 doing something here;
 if ($debug === true){
  echo 'SOMETHING';
 }else{
  return true;
 }
}

This way you can debug something bu simply adding the variable to the function call but if you dont' add it the functions assumes it is false. This is valuable in my $_GET security function that I am using to encrypt my $_GET strings when I turn on debug the $_GET is decoded and dumped as an array inside a

<pre>print_r($_GET);</pre>

so that I can see what the values are in the $_GET but the string is still encrypted in the address bar.

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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