Nat*_*han 0 php parameters function
例:
function example($x = "")
{
Do something
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,$ x是否已空?为什么要明确设置?
默认情况下,$ x是否已空?
如果未指定default,$x则默认情况下不是空字符串,而是未定义的变量.""和/ NULL或undefined 之间存在差异.
但是,设置默认值允许您在调用函数时省略参数,而不会发出警告.
<?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
Run Code Online (Sandbox Code Playgroud)