If $bar
not defined, there really is no βshorterβ way to write the same code.
There are two that I consider "hacks" for this, however they can also influence other things:
- Throttling error with
@
, for example $foo = @$bar ?: $baz;
, will do exactly what you want and activate undefined -error, which if $bar
undefined. If defined, it will also work as desired. However, the downside is that @
can reduce the efficiency in your code if it is reused. - Disabling notifications using
error_reporting(E_ALL & ~E_NOTICE);
. This will still display all regular errors, but simply not notifications that will effectively hide the "undefined variable" error. The disadvantage of this is that you will not see any other notifications.
Now, my mandatory personal opinion, I would advise you to continue to write it in full. The ternary operator is already shortened, effectively reducing the following:
if (isset($bar)) { $foo = $bar; } else { $foo = $baz; }
in a much shorter
$foo = isset($bar) ? $bar : $baz;
and in fact, it doesnβt take much more effort to write a full triple and a shorter triple (unless, of course, the names of the variables are ridiculously long). In addition, there will be several examples when complex ternary operations (i.e. several triple in one), which will lead to the fact that unnecessary shorthand will become unsuitable; therefore, short-term savings are not programmatically / morally satisfactory (in my opinion).
UPDATE:. To support your editing, in which you assign $bar
return value of the function, and then $foo
based on it, you can combine the operators in a single -line like:
$foo = (($bar = $some->reallyExpensiveOperation()) != null) ? $bar : $baz;
This is almost the same code length as two lines, but here it can also be shortened a bit. For example, if null
not the only value that you consider to be "invalid", but false
also taken into account, you can completely remove the != null
and allow the condition to be considered as a simple Boolean value:
$foo = ($bar = $some->reallExpensiveOperation()) ? $bar : $baz;
In this example, $bar
is still available after the triple operation (i.e., it does not lose its scope), so if you do not need to preprocess the variable, there is no big drawback in this method, except for readability.