| Subject | Details |
| :------------- | :---------------------------------------------------------------------------- |
| Plugin | Php Inspections (EA Extended) 4.0.6 |
| Language level | PHP 7.4 |
$y = '1'; $z = 2;
$x = (int) $y ?? $z;
// ~~~~~~~~ [EA] The operation results to '(int) $y', please add missing parentheses.
$x = ((int) $y) ?? $z;
// ~~~~~~~~ [EA] The operation results to '(int) $y', please add missing parentheses.
$x = (int) ($y ?? $z); // no error reported, but not what I want.
I assumed this inspection was intended to make explicit whether the cast was to be applied to the result of the entire null coalescing statement or just the first operand. Unfortunately adding clarifying parentheses does not remove the warning.
At least the second case with added parentheses should be valid.
In this particular case, I don't even think the clarifying parentheses should be required, so the first example should be valid as well. It is very obvious that a cast is applied to the next variable immediately following it and not the whole expression. The ?? provides a clear separation of intent. Of course this is a judgement call. I would rather not turn off the inspection entirely.
IntelliJ IDEA 2020.2.3 (Ultimate Edition)
Build #IU-202.7660.26, built on October 6, 2020
The first and second examples don't make sense, because (int) $y evaluates to 0 if $y is null.
Thus, ?? $z would never be evaluated and could be removed.
This means only the third example is correct.
Most helpful comment
The first and second examples don't make sense, because
(int) $yevaluates to0if$yisnull.Thus,
?? $zwould never be evaluated and could be removed.This means only the third example is correct.
See: https://3v4l.org/rgVQQ