Re: nested, referenced foreach & implicit current array pointer issues

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2007/1/30, speedy <speedy.spam@xxxxxxxxx>:

Hello PHP crew,

As a followup to:

http://bugs.php.net/bug.php?id=22879


That's not a bug, just an user doing things the wrong way and blaming the
language.

I've stumbled upon this problem in a way:

function f()
{
   global $arr;

   foreach($arr as $k=>$v) {
       $v->do_something();
   }
}

After digging through the docs I found that $arr is in fact a reference to
original $arr, and (in a pretty complex/confusing doc. page about foreach)
came to a conclusion that the above construct is practically unusable with
the global keyword as do_something() can potentially affect $arr hidden &
implicit (*yuck*) current element pointer and thus quite _non-obviously_
side-effect parent foreach() (ie. side-effect hidden in the depths of its fn
calls).

It would be (perhaps) better if PHP would treat global as making globaly
defined $arr accessible from the local fn. namespace instead of assigning a
local name to be a reference?

Also if the price of implicit current element pointer is copying of
non-referenced array on foreach() to gain humanly-expected behaviour,
and its great potential of writing non-obvious/bad code, I must wonder if
there are any good use cases (except the trivial ones) where  current
pointer is actually fruitful?


I don't see your point anywhere... foreach iterates over a copy of the array
so where is the potential side-effect? Even so there will be references if
the items of the original array are references, or if they are objects in
PHP5, but that's expected behaviour. That's the way many OOP languages have
been implemented (eg: Java) without coders having the problems you mention.
Just give me one good reason to even consider your proposal.

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux