当为可为空的函数参数指定`null'时,如何使用默认值? [英] How to use default value when `null` is given for a nullable function parameter?
问题描述
在PHP 7.1中,调用以下函数时:
In PHP 7.1 when the following function is called:
private function doStuff(?int $limit = 999) { }
具有如下语法:
doStuff(null);
$ limit
的值变为 null
.因此,我想可以说 $ limit
的值已显式设置为 null
.
the value of $limit
becomes null
. So I guess it can be said that the value of $limit
was explicitly set to null
.
有什么办法可以克服这个问题?IE.当遇到空值(即缺少值)时,请使用默认值,是隐式还是显式?
Is there any way to overcome this? I.e. when a null value (i.e. the lack of a value) is encountered use the default, whether it is implicit or explicit?
推荐答案
没有PHP没有如果为null则默认还原"选项.您应该改为:
No PHP doesn't have a "fallback to default if null" option. You should instead do:
private function dostuff(?int $limit = null) {
// pre-int typehinting I would have done is_numeric($limit) ? $limit : 999;
$limit = $limit ?? 999;
}
或者,当您没有明智的做事价值时,请确保您执行 dostuff()
或 dostuff(999)
.
Alternatively make sure you either do dostuff()
or dostuff(999)
when you don't have a sensible value for doing stuff.
注意:也有一些反思可以获取方法参数的默认值,但这似乎太多了.
Note: There's also reflection to get the default values of method parameters but that seems a too much.
但是,方法如下:
$m = new ReflectionFunction('dostuff');
$default = $m->getParameters()[0]->getDefaultValue();
dostuff($default);
这篇关于当为可为空的函数参数指定`null'时,如何使用默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!