On 06/23/2011 05:09 PM, Ferenc Kovacs wrote:
> On Thu, Jun 23, 2011 at 5:03 PM, Stefan Neufeind <neufe...@php.net> wrote:
> 
>> I've lately discussed with a colleague which scopes of variables exist
>> for PHP or would probably make sense. In general I think the general
>> idea of having variables available all throughout a function is okay as
>> this allows things like

[...]

>> (setting $found inside the loop while still being able to access it
>> outside)
>>
>> But the interesting part is that $v is also still available outside the
>> loop (last value). While most people would say this is not a big
>> problem, it can become problematic when using references.

[...]

> it was discussed many times on the list,

That's what I feared.

> and this behavior is also documented, see
> http://php.net/manual/en/control-structures.foreach.php
> 
> "Reference of a $value and the last array element remain even after the
> foreach loop. It is recommended to destroy it by unset()."

Yes, I should have included that reference. While it's in the docs, I
don't think many people know about it. As said, with normal variables
it's no real problem either (forgetting about a $temp-variable). But
with references it becomes a problem.
We've introduced some reference-usage in TYPO3-project lately and that's
where somebody mentioned "remember to use unset()", which I wasn't
really aware of I must admit.

> personally I find that weird, and unintuitive, but changin that in a major
> or minor version could be changed if we chose to.

I think it's a behaviour that could be changed in some step like from
5.3 to 5.4 or so. Personally I don't think it would influence existing
implementations much (who uses the key/value of a foreach after the
loop?) or could easily be changed.

While the new behavior might sound "weird" at first sight, it partially
replicates scoping that other languages already do. And (especially for
the references-case) it might even prevent some unplanned, maybe hard to
debug problems (if you forget to unset()).


Kind regards,
 Stefan

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

Reply via email to