Re: Unsetting loop variables at the end of the loop
| From: | Rasmus Lerdorf | Date: | Mon, 28 Dec 2009 01:57:00 +0000 |
| Subject: | Re: Unsetting loop variables at the end of the loop | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-46534@lists.php.net to get a copy of this message | ||
jvlad wrote:
> "Rasmus Lerdorf" <rasmus@lerdorf.com> wrote in message
> news:4B3785AC.2000507@lerdorf.com...
>> We can't just randomly reset variables based on their scope in this one
>> specific case. If we are going to "fix" this, it should be done by
>> introducing a way to do proper local scope variables. Resetting a
>> reference simply because it is convenient in this one case would be
>> completely inconsistent.
>>
>> -Rasmus
>
> Rasmus,
> it's not required to do anything like that and I myself would be against any
> random resets,
> but it's definitely not the case. There is nothing random and everything is
> well determinted.
> As I see the problem, it would be sufficient to fix the FOREACH and make it
> working in the following way:
> For example, say we have $a=array('apple', 'orange');
> and iterate through $a values:
> foreach($a as &$v) ...
> as an initial step, $v MUST be assigned to the very first element of $a
> which 'apple'. It should be done regadless of the
> value that might be assigned to $v before (that's the first change)
> On the next step, it will be advanced by one and assign $v to point to
> 'orange'
> On the next iteration, it MUST also be advanced by one, reach the End Of the
> Array, so it should assign NULL (or FALSE?) value to $v,
> then finish the loop.
>
> Isn't it what would work in a clearer way?
>
> Evenmore, this change would make the foreach working more consistent with
> each()/next()/prev() - they return FALSE as soon as internal pointer
> reaches either boundary of the array. Neither stick with last element, like
> foreach().
>
> If you think current behaviour of foreach is useful, it's possible to
> introduce new setting in php.ini, say strict_foreach=ON that will break
> BC, but make foreach working clearer.
No chance. No .ini settings, and I still maintain it is inconsistent.
So, if I write this:
$a = array(1);
$b = 0;
$c = &$b;
$c = $a[0];
Would you agree that $b should be 1 at this point? If so, just because
I rewrite that code like this:
$a = array(1);
$b = 0;
$c = &$b;
foreach($a as $c);
Now you are arguing that $b should not be 1?
The two pieces of code are identical and since we do not have a block
scope and there is no syntax for explicitly indicating that $c is
somehow a different $c or that we should wipe out the $c that existed
before the foreach, I can see no sane reason to break the language for
this case.
And I don't see how your prev/next stuff has anything to do with this.
-Rasmus