Hacker News new | ask | show | jobs
by anaphor 4497 days ago
It is an algorithm used in compiling languages like Scheme where you calculate the set of free variables in a function and then create a closure (a function pointer and an environment, which is basically a way to lookup free variables). PHP requires you to do this by hand with the "use" keyword, e.g. use($a, $b, $c) where $a, $b, and $c are free variables (that is they are not bound in the current scope). I see no reason why PHP couldn't be doing this for you other than that the devs are lazy.
1 comments

AFAIK, `use` were required because PHP has variable-variables:

    <?php
    $x = "b";
    $b = 42;
    echo $$x; // equivalent to echo $b;

    // Here the compiler can't determine all the variables
    // used in the function.
    // Has a result, there were two choices:
    // - capture the whole environment
    // - capture explicitly named variables

    function () {
        return $$x;
    }
Hopefully, nobody uses variable-variables these days, however this is the reason behind the introduction of `use` for closures.
Yep that occurred to me after I posted this, but I believe it should be possible to exclude variable variables from this at the cost of a runtime error if you try to use them in a closure. Someone else pointed out to me that PHP has other ways of messing with variables as well and that it would require full evaluation to determine all of them, so maybe it "makes sense", but only because of the extremely dynamic nature of variables in PHP.