gpt4 book ai didi

php - 在函数中使用默认参数

转载 作者:IT老高 更新时间:2023-10-28 11:42:56 24 4
gpt4 key购买 nike

我对 PHP 函数的默认值感到困惑。假设我有这样的功能:

function foo($blah, $x = "some value", $y = "some other value") {
// code here!
}

如果我想为 $x 使用默认参数并为 $y 设置不同的参数怎么办?

我一直在尝试不同的方法,但我越来越困惑。比如我试过这两个:

foo("blah", null, "test");
foo("blah", "", "test");

但是这两个都不会导致 $x 的正确默认参数。我也试过用变量名来设置它。

foo("blah", $x, $y = "test");   

我完全期望这样的事情能够奏效。但它根本不像我预期的那样工作。似乎无论我做什么,每次调用该函数时,我最终都必须输入默认参数。而且我一定遗漏了一些明显的东西。

最佳答案

我建议按如下方式更改函数声明,以便您可以随心所欲:

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 仍然得到它的默认值。

使用此方法,传递空值意味着当您想要覆盖其后参数的默认值时,您需要一个参数的默认值。

如其他答案所述,

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 给出的答案的函数。

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

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!");
}
}

关于php - 在函数中使用默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9166914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com