How to use default value when `null` is given for a nullable function parameter? How to use default value when `null` is given for a nullable function parameter? php php

How to use default value when `null` is given for a nullable function parameter?


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