I often find myself needing to write code with the following logical pattern:
$foo = isset($bar) ? $bar : $baz;
I know about the ?:
syntax:
$foo = $bar ?: $baz;
...which, on the surface, appears to be what I'm looking for; however, it throws an undefined notice index when $bar
is not set. It also uses the same logic as empty()
, meaning that "empty" values like FALSE
, 0
, "0"
, etc. don't pass. Hence, it's not really equivalent.
Is there a shorter way of writing that code without throwing a notice when $bar
is not set?
Edit:
To make it a bit more clear why I'm looking for a shortcut syntax, here's a better example:
$name = isset($employee->getName())
? $employee->getName()
: '<unknown>';
In this case, $employee
might be an object from a 3rd-party library, and it might be a valid scenario that its name
might be NULL
. I'd like to set variable $name
to the returned name (if there is one), but some sensible default if there isn't.
If the method call is more complex than just a getter, then the example becomes even more verbose, since we have to cache the result:
$bar = $some->reallyExpensiveOperation();
$foo = isset($bar) ? $bar : $baz;
I would only use the short hand ternary syntax when you explicitly predefine your variables or use an object with a magic getter. This is a very basic example of where I would normally use short hand ternary syntax
class Foo {
public function __get($name) {
return isset($this->{$name}) ? $this->{$name} : '';
}
}
$foo = new Foo();
$bar = $foo->baz ?: 'default';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With