I'm currently passing a value - which might be null - to a function that has a default value for that parameter. I expected that if the parameter is null, it would return the default value. But that does not seem to be the case. Now I was wondering if there is a way to work around this?
I know I can check if the value is null, and don't pass it when it is, but I don't want to have too many if's in my code. I just want a clean way to grab the default value if it's null.
Some extra info: I'm using Laravel framework 8 - maybe some nice functions in Laravel I don't know yet.
Example code:
<?php
class Person {
private $name;
public function greet(string $greeting = 'Hello')
{
return sprintf('%s %s', $greeting, $this->name);
}
public function setName($name)
{
$this->name = $name;
return $this;
}
}
$externalInput = null;
$person = (new Person())->setName('Maik');
echo $person->greet($externalInput);
This is just an example code, so don't mind the security issues this might have. That's all taken care off in my real code. This code is just to illustrate the problem I'm having.
$person->greet(null)to give the same result as$person->greet()&$person->greet('Hello')?if ($greeting === null) ....nullis not the same as omitting an argument with a default value, so no, you cannot do it at language level. See @Bart's answer below. That's the closest you can get.