1

在 Python 中,可以有一个包含多个变量的函数,这些变量都具有默认值。然后只是传递其中一个值的值。所以如果我有

function foo(a=10,b=50, c=70)
    pass
    pass
    return

然后我可以打电话

foo(b=29)

它会调用

foo(10,29,70) 

(使用所有值的默认值,以及该变量的确切值)。

PHP中有类似的可能吗?

4

2 回答 2

1

不,没有与 PHP 中的等价物。您可以为函数参数设置默认值,但它们是从左到右计算的并且没有命名:

function test($var1 = 'default1', $var2 = 'default2')
{

}

在该示例中,这两个变量是可选的,但如果要指定第二个参数,则必须指定第一个参数。

test(); // works
test('arg1'); // works
test('arg1', 'arg2'); // works
test('arg2'); // this will set the first argument, not the second.

如果您需要对可选参数具有灵活性,一种常见的解决方法是将数组作为参数传递:

function test($options)
{

}

这可以具有单个关联数组形式的可变数量的参数:

$options = array('var1' => 'arg1', 'var2' => 'arg2');
test($options);
于 2013-01-05T16:42:27.750 回答
1

使用数组作为参数。例如:

function a(array $params) {
    $defaults = array(
        'a' => 10,
        'b' => 50,
        'c' => 70,
    );
    $params += $defaults;
    // use $params
}

a(array('b' => 29));
于 2013-01-05T16:43:20.343 回答