简体   繁体   English

人们为什么在PHP函数中设置默认参数?

[英]Why do people set default parameters in PHP functions?

Example: 例:

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

Isn't $x empty by default already? $ x默认情况下是否为空? Why set it explicitly? 为什么要明确设置?

Isn't $x empty by default already? $ x默认情况下是否为空?

If no default is specified, $x is not an empty string by default, but an undefined variable. 如果未指定默认值,则$x默认情况下不是空字符串,而是未定义的变量。 There is a difference between "" and NULL or undefined. ""NULL或未定义之间有区别。
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. 当默认设置为true或false时,会发生很多情况。 That way a function can seem to be overloaded like you can do in other oop languages. 这样,函数似乎可以像其他oop语言一样重载。 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. 这样,您可以调试一些事情,只需将变量添加到函数调用中即可,但是如果不添加变量,函数将假定它为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 这在我的$ _GET安全功能中很有价值,当我打开调试功能时,该功能会用来加密$ _GET字符串,$ _ GET会被解码并作为数组转储到

<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. 这样我就可以看到$ _GET中的值,但是该字符串仍在地址栏中进行了加密。

Hope that helps 希望能有所帮助

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

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