Web lists-archives.com

[PHP] Unsetting the "by-reference" variable in foreach().




Hi.

A very common pattern and the one that is documented is ...

<?php
$collection = [];
foreach($collection as &$item) {
  // Payload.
}
unset($item);

>From PHP's perspective, this is all fine.

>From a static analysis perspective though, $item is a problem in the
unset().

In the above code, $item will not exist as the collection is empty.


So, with regard to that issue, how does this code fair?

<?php
$collection = [];
foreach($collection as &$item) {
  // Payload.
  unset($item);
}

Here the unset() happens at the end of the foreach() iteration.

I'm thinking PHP will be quite happy with this as long as the unset($item)
occurs after all usages of $item.

And static analysis is happy as $item isn't referenced out of scope.


Considering more and more automation tools exist and static analysis is
becoming part of that tool chain (I am using PHPStan), should any
consideration be given to this sort of issue?

Anyway, beside that, anyone got any opinions, thoughts?

Regards,

Richard Quadling.