You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When performing a foreach on an array, you can use the dangling reference of the loop ($things as $thing, you can use $thing still after the loop), but of course if the count of the array is zero, then $thing is rightly pointed out to be possibly not defined (Variable $thing might not be defined.). However, if we check the count($things) is non-zero before the iteration, phpstan should notice this and be satisfied that $thing would always be set.
<?phpdeclare(strict_types = 1);
classThing { publicfunctionfoo() : void {} }
/** @var Thing[] $things */$things = [newThing(), newThing()];
// This count check should tell phpstan that $thing exists down belowif (count($things) === 0) {
// it's return from a method in our case, but die for example sake
die();
}
foreach ($thingsas$thing) {
}
/** @var Thing $thing */$thing->foo();
Actual output
------ ---------------------------------------
Line analyzed.php
------ ---------------------------------------
18 Variable $thing might not be defined.
------ ---------------------------------------
Expected output
I expect no errors, the detected issue is a false positive.
The text was updated successfully, but these errors were encountered:
Thanks folks! I'm happy for this to be a duplicate of #1073 then (assuming they would be solved using the same approach). Meanwhile, workarounds work 👍
Summary of a problem or a feature request
When performing a
foreach
on an array, you can use the dangling reference of the loop ($things as $thing
, you can use$thing
still after the loop), but of course if the count of the array is zero, then$thing
is rightly pointed out to be possibly not defined (Variable $thing might not be defined.
). However, if we check thecount($things)
is non-zero before the iteration, phpstan should notice this and be satisfied that$thing
would always be set.Code snippet that reproduces the problem
See results: https://phpstan.org/r/48ec08fa293fa3ac9857d2c975188a13
Actual output
Expected output
I expect no errors, the detected issue is a false positive.
The text was updated successfully, but these errors were encountered: