Re: Lexical scoping

From: Date: Tue, 28 Jan 2014 13:36:34 +0000
Subject: Re: Lexical scoping
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-71670@lists.php.net to get a copy of this message
On 28 January 2014 13:25, Lazare Inepologlou <linepogl@gmail.com> wrote: > 2014-01-28 Sebastian Krebs <krebs.seb@gmail.com> > > > 2014-01-28 Andrea Faulds <ajf@ajf.me> > > > > > Good morning, > > > > > > Perhaps a future version of PHP (PHP 6? 5.7?) could have lexical > scoping > > > with a > > > "let" keyword? At the very least, it would make foreach() with a > > reference > > > less > > > of a problem: > > > > > > foreach ($array as let &$a) { > > > $a = 3; > > > } > > > // $a is not in this scope - no need to worry about accidentally > > > changing > > > last array item > > > > > > Any thoughts? > > > > > > > Hi, > > > > My 2 cents: That is a very minor improvement at the cost of an additional > > keyword. It is only to avoid, that you accidentally interfere with outers > > scope variables? If it is hard to track these variables, maybe your > > method/function is too big. > > > > > I agree. > > > > Regarding your example: > > > > foreach ($array as &$a) { > > $a = 3; > > } > > $a = null; // $a not a reference anymore. Problem solved :) > > > > > Problem not solved. You have just changed the last element of $array... > This is the exact problem that was to be avoided. > > AFAIK, this is a problem which is quite limited to foreach() (are there other examples?), so one (BC-breaking-but-probably-for-the-best) solution would simply be to unset the variable automatically if it wasn't already defined: foreach( $array as &$a ){ $a = 3; } var_dump( $a ); // E_NOTICE, $a is now undefined $b = 2; foreach( $array as &$b ){ $b = 3; } var_dump( $b ); // 3, $b was defined before we started the foreach, so it's not wiped Alternatively, you could say that the ultimate problem is that we don't have strong scoping - braces only define flow control, not scope. So you could introduce a strong-scoping structure. Maybe a double brace? foreach( $array as &$a ){{ $a = 3; }} var_dump( $a ); // E_NOTICE, $a is now undefined You could even say that an isolated brace pair (ie not one following a control statement) *always* produces a scope. --GB

« previous php.internals (#71670) next »