php默认参数

JDe*_*gns 19 php arguments

在PHP中,如果我有一个这样的函数

function example($argument1, $argument2="", $argument3="")
Run Code Online (Sandbox Code Playgroud)

我可以在其他地方调用此函数

example($argument1)
Run Code Online (Sandbox Code Playgroud)

但是,如果我想给thrid参数赋予一些价值,我应该这样做

example($argument1, "", "test");
Run Code Online (Sandbox Code Playgroud)

要么

 example($argument1, NULL, "test");
Run Code Online (Sandbox Code Playgroud)

我认为两者都会奏效,但更好的方法是什么?因为将来如果在main函数中更改$ argument2的值并且如果我有"",那么会有任何问题吗?或NULL是最好的选择?

谢谢

Mar*_*c B 15

传递null或者""您不想指定的参数仍会导致传递给函数的那些空值和空字符串.

使用参数的默认值的唯一情况是参数在调用代码中是否为NOT ALL.example('a')将args#2和#3设为默认值,但如果你这样做,example('a', null, "")那么arg#3为null,arg#3是函数中的空字符串,而不是默认值.

理想情况下,PHP会支持类似于example('a', , "")允许将默认值用于arg#2的东西,但这只是一个语法错误.

如果你需要在函数调用中间保留参数但是为后面的参数指定值,则必须在函数本身中显式检查一些sentinel值并自己设置默认值.


这是一些示例代码:

<?php

function example($a = 'a', $b = 'b', $c = 'c') {
        var_dump($a);
        var_dump($b);
        var_dump($c);
}
Run Code Online (Sandbox Code Playgroud)

并为各种输入:

example():
string(1) "a"
string(1) "b"
string(1) "c"

example('z'):
string(1) "z"
string(1) "b"
string(1) "c"

example('y', null):
string(1) "y"
NULL
string(1) "c"

example('x', "", null):
string(1) "x"
string(0) ""
NULL
Run Code Online (Sandbox Code Playgroud)

请注意,只要在函数调用中为参数指定ANYTHING,该值就会传递给函数并覆盖函数定义中设置的默认值.


Pee*_*Haa 11

你可以使用:

example($argument1, '', 'test');
Run Code Online (Sandbox Code Playgroud)

要么

example($argument1, NULL, 'test');
Run Code Online (Sandbox Code Playgroud)

您始终可以使用而不是空字符串来检查NULL:

if ($argument === NULL) {
    //
}
Run Code Online (Sandbox Code Playgroud)

我认为这完全取决于使用args在函数内部发生的事情.