On Wed, Feb 1, 2017 at 8:05 AM, Bruce Weirdan <weir...@gmail.com> wrote:

> On Wed, Feb 01, 2017 at 07:45:50AM -0800, Rasmus Lerdorf wrote:
> > The reason it is feasible to do this for single-expression closures in
> this
> > short form syntax is that you don't typically need a local scope at all
> for
> > these short closures and the syntax doesn't convey the idea that you
> would
> > have a local scope.
>
> Does this mean, in the context of this RFC, that short-form lambdas
> won't have their own scope though? I think it's not clear from RFC.
>
> Example:
> // would this create $ret in the outer scope assuming $ret was not
> // defined
> array_map(fn($elt) => $ret[] = $elt, [1]);
> var_dump($ret); // NULL or array(1) ?
>
> Current implementation (available on 3v4l.org) does create a local
> scope, but it should probably be explicitly stated in the RFC (and
> docs, should the RFC get accepted).
>

I actually tend to think of these short-form lambdas as not having a local
scope. That might sound a bit odd, but let me demonstrate:

    $f = fn() => print($var=1);
    $f();
    echo $var;

This should output 1 and then give a notice about $var being undefined on
the echo. You probably think of $var as being a local scope variable here,
but really it isn't. It is an imported variable that happened to not exist
in the outer scope and it was assigned a value in the inner scope, but that
assignment can't leak back out so it is still unassigned in the outer
scope. I think of it this way, because if you do:

    $var = 3;
    $f = fn() => print(++$var);
    $f();
    echo $var;

You should see: 43

$var did not originate in the inner scope, it was imported from the outer
scope by-value and reassigned. To me, automatic import precludes the notion
of a local scope entirely. When a variable you use within the lambda isn't
defined in the outer scope it acts exactly like a locally scoped variable,
but it isn't, because defining it in the outer scope could potentially
affect it depending on how it is used within the lambda.

-Rasmus

Reply via email to