btwael / mammouth

Unfancy PHP
http://mammouth.boutglay.com
MIT License
214 stars 22 forks source link

Support lexically scoped 'use' variables #1

Closed tmzt closed 8 years ago

tmzt commented 11 years ago

PHP 5.3+ supports a type of function syntax used for closures which allows variables to be passed, by value or reference, into the scope of the function.

Example:

$shared = 3;

function ($a) use (&$shared) {
    echo "In function before assignment: shared: " .  $shared;
    $shared = 5;
    echo "In function after assignment: shared: " . $shared;
}

echo "After function: shared: " . $shared;

It would be nice if mammouth either supported a variant of the 'use' syntax, or intelligently supported lexically scoped variables being used inside of function bodies.

btwael commented 11 years ago

@tmzt , maybe we will use a syntax like that as variant of the use:

foo = (a)(shared) ->
    echo("In function before assignment: shared: " + $shared)
    shared = 5
    echo("In function after assignment: shared: " + $shared)

compiled to

function ($a) use (&$shared) {
    echo "In function before assignment: shared: " .  $shared;
    $shared = 5;
    echo "In function after assignment: shared: " . $shared;
}
philip-peterson commented 11 years ago

What about just something like:

shared = "3"
foo = (a) ->
    echo("In function before assignment" + shared)

Since the compiler knows there's no inner variable named shared, it can safely assume there's an outer one. The trickiness comes in when you want to define an inner variable.

shared = "3"
foo = (a) ->
    shared = "4"
    echo("In function before assignment" + shared)

In the above, are we assigning the outer one or the inner one? Coffeescript just assumes we wanted the outer one and gives us no easy way to mean the inner one (and a lot of people dislike Coffeescript for this reason).

One solution would be to have an optional "variable delcaration" syntax. I won't write that one down though because it's not very elegant to me. Coco, a competitor to Coffeescript, solves the problem by having this syntax:

shared = "3"
foo = (a) ->
    shared := "4"
    echo("In function before assignment" + shared)

The colon in line 3 indicates that shared means the outer variable. If there were no colon, it would've declared a new inner variable.

avarayr commented 8 years ago

+1. We really need this