PHP8 ?-> in IF statements

Viewed 19

In the old PHP, IF statements were written as

if ($a && $a->b()) {
    ...
}

Can the above be written in PHP8 as

if ($a?->b()) {
    ...
}

Can a class method be used simply (without equation) as

$a?->b();

instead of

if ($a) {
    $a->b();
}
1 Answers

The two statements are not technically equivalent, but may be what was intended.

The ?-> operator is called the nullsafe operator, and is specifically checking the left-hand side for null. As that manual page says:

The effect is similar to wrapping each access in an is_null() check first, but more compact.

So the following are all equivalent

if (is_null($a) && $a->b()) {
    echo 'here';
}

if ($a === null && $a->b()) {
    echo 'here';
}

if ($a?->b()) {
    echo 'here';
}

However, that's not quite what you wrote; you used $a by itself "in boolean context", meaning all you were checking for was that it was "truthy" or "not empty". To demonstrate, consider this:

$a = false;
if ($a && $a->b()) {
    echo 'here';
}

Here the existing code will shortcut, but a nullsafe operator would not. A fully verbose version of the intention might look like this:

$a = true;
if ($a instanceof SomeClass && $a->b()) {
    echo 'here';
}

In practice, you probably already know that $a is either the correct object or null (e.g. it's passed a ?SomeClass type constraint on a parameter or property), in which case yes, the ?-> nullsafe operator means you no longer need the extra check.

Related