Hi,

A week or two ago, a colleague asked me about a strange behaviour he
experienced, with seemingly-duplicate data within a foreach block. Upon
further examination, we determined that this was caused by assigning to
a referenced variable:

<?php
$i = array('zero','one','two');
foreach ($i AS &$j) {}
foreach ($i AS $j) {
  echo $j . " ";
}
?>

(Output is: "zero one one")

I asked around about this, and was given the technical explanation (see
http://sean.caedmon.net/notsoweird.phps if you're curious), which
cleared it up.

However, upon further discussion, a number of us agreed that it would be
pertinent to raise an E_NOTICE when foreach assigns to a pre-existing
reference target. Certainly, the behaviour demonstrated above is
non-obvious, and contrary to the normal "PHP way" (simplicity).
Developers, at least in my opinion, don't expect foreach to WRITE to the
iterated array.

Technical explanation aside (yes, we realize that this is "normal"
behaviour, as demonstrated in the unroll), I believe this represents a
usability problem.

Can we throw an E_NOTICE when foreach targets a reference? (The other
option we kicked around was implicitly unset()ing the target variable
before the first iteration, but this was deemed "too magical".)

If so, when? HEAD only? I'd like to see it in 5.2 as well, if that ever
exists, but I agree that it's too late for 5.1.

S

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to