且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在函数中使用默认参数

更新时间:2022-12-04 17:05:01

我建议更改函数声明如下,这样你就可以做你想做的事:

I would propose changing the function declaration as follows so you can do what you want:

function foo($blah, $x = null, $y = null) {
    if (null === $x) {
        $x = "some value";
    }

    if (null === $y) {
        $y = "some other value";
    }

    code here!

}

这样,你可以像 foo('blah', null, 'non-default y value'); 这样的调用,让它按你想要的方式工作,其中第二个参数 $x 仍然是它的默认值.

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

使用此方法,传递空值意味着当您想覆盖后面的参数的默认值时,您需要该参数的默认值.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

如其他答案所述,

默认参数仅用作函数的最后一个参数.如果要在函数定义中声明默认值,没有办法省略一个参数并覆盖它后面的一个.

default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.

如果我有一个方法可以接受不同数量的参数和不同类型的参数,我通常会声明类似于 Ryan P 给出的答案的函数.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

这是另一个例子(这不能回答你的问题,但希望能提供信息:

Here is another example (this doesn't answer your question, but is hopefully informative:

public function __construct($params = null)
{
    if ($params instanceof SOMETHING) {
        // single parameter, of object type SOMETHING
    } elseif (is_string($params)) {
        // single argument given as string
    } elseif (is_array($params)) {
        // params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
    } elseif (func_num_args() == 3) {
        $args = func_get_args();

        // 3 parameters passed
    } elseif (func_num_args() == 5) {
        $args = func_get_args();
        // 5 parameters passed
    } else {
        throw new \InvalidArgumentException("Could not figure out parameters!");
    }
}