调用函数时使用默认值

mat*_*thy 14 php default-arguments

在PHP中,您可以调用函数.通过使用这些语句不调用所有参数.

function test($t1 ='test1',$t2 ='test2',$t3 ='test3')
{
echo "$t1, $t2, $t3";
}
Run Code Online (Sandbox Code Playgroud)

你可以使用这样的功能

test();
Run Code Online (Sandbox Code Playgroud)

所以我只想说我希望最后一个是不同的而不是其他的.我能做到的唯一方法是做到这一点,但没有成功:

test('test1','test2','hi i am different');
Run Code Online (Sandbox Code Playgroud)

我试过这个:

test(,,'hi i am different');
test(default,default,'hi i am different');
Run Code Online (Sandbox Code Playgroud)

做这样的事情的最佳方法是什么?

小智 25

使用数组:

function test($options = array()) {
    $defaults = array(
        't1' => 'test1',
        't2' => 'test2',
        't3' => 'test3',
    );
    $options = array_merge($defauts, $options);
    extract($options);
    echo "$t1, $t2, $t3";
}
Run Code Online (Sandbox Code Playgroud)

以这种方式调用您的函数:

test(array('t3' => 'hi, i am different'));
Run Code Online (Sandbox Code Playgroud)

  • 呃,打败我吧.举个例子,`extract`很好但是对于现实世界的使用,没有必要声明那么多变量.只是想注意;) (2认同)

Joo*_*ost 10

你不能使用原始PHP来做到这一点.您可以尝试以下方式:

function test($var1 = null, $var2 = null){
    if($var1 == null) $var1 = 'default1';
    if($var2 == null) $var2 = 'default2';
}
Run Code Online (Sandbox Code Playgroud)

然后使用null默认变量的标识符调用您的函数.您还可以使用具有默认值的数组,使用更大的参数列表会更容易.

更好的是尽量避免这一切,并重新考虑你的设计.


JAL*_*JAL 2

在 PHP 中,具有默认值的参数必须位于最后,在其他参数之后,并且在调用函数时必须填写到此为止的所有其他参数。我不知道如何传递触发默认值的值。