Error on using nullsafe property access on empty array #4688
-
Hi, before opening an issue, I wanted to check opinions on the following error. <?php declare(strict_types = 1);
/** @var array<stdClass> $array */
$array = [];
echo $array[0]?->maybeNotThere ?? 'else this';
/** @var array<stdClass|null> $array */
$array = [];
echo $array[0]?->maybeNotThere ?? 'else this'; See: https://phpstan.org/r/a203fb57-a5f8-48df-b652-1cfcd01b0607 This code emits
I thought the nullsafe property access is intended to be used like the nullsafe operator The second array declaration If the array is empty, an access like TL;DR What do you think? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Consider this: https://3v4l.org/WB2UW You're getting a warning for accessing an undefined array key. The ?-> operator should only save you from getting "calling method on null": https://3v4l.org/Bsuoc (still getting a warning) It's a bit messy because you're not getting the warning thanks to ?? operator afterwards: https://3v4l.org/jdNaC I'd say that in this situation, code that uses just -> works identically: https://3v4l.org/paRS1 So PHPStan's error "Using nullsafe property access on non-nullable type stdClass. Use -> instead." is actually correct I'd say. WDYT? |
Beta Was this translation helpful? Give feedback.
Consider this: https://3v4l.org/WB2UW You're getting a warning for accessing an undefined array key. The ?-> operator should only save you from getting "calling method on null": https://3v4l.org/Bsuoc (still getting a warning)
It's a bit messy because you're not getting the warning thanks to ?? operator afterwards: https://3v4l.org/jdNaC
I'd say that in this situation, code that uses just -> works identically: https://3v4l.org/paRS1
So PHPStan's error "Using nullsafe property access on non-nullable type stdClass. Use -> instead." is actually correct I'd say. WDYT?