PHP 7.1 Nullable Default Function Parameter

蓝咒 提交于 2019-12-10 02:54:18

问题


In PHP 7.1 when the following function is called:

private function dostuff(?int $limit = 999) { }

with syntax like so:

dostuff(null);

the value of $limit becomes null. So I guess it can be said that the value of $limit was explicitly set to null. 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?

Thanks


回答1:


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;
}

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.

However here's how:

 $m = new ReflectionFunction('dostuff');
 $default = $m->getParameters()[0]->getDefaultValue();
 dostuff($default);


来源:https://stackoverflow.com/questions/45320353/php-7-1-nullable-default-function-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!