On 2/24/10 8:56 AM, Stanislav Malyshev wrote:
Hi!

Correct me if I'm wrong, but given the fact that PHP only* supports
functions defined in the global space**, with the additional ability to
import global variables using the global statement, wouldn't that make
named functions able to close-over global variables?

It's different mechanism. Globals are just references to variables in
same global scope, they are not bound to any function, etc.

And, if the above is true, wouldn't it be consistent to support the use
statement on named functions, and then deprecate the global statement?

That's why I'm not a big fan of that "consistency" argument here on the
list - because it usually means "let's implement some feature because I
like it", but not more. Which is fine, but it has nothing to do with
consistency.
Particularly, scope capturing and all that has very little relation to
what globals do. Closures carry around "captured" variables. Regular
functions don't. Global scope exists independently of them.
The mechanism is similar (well, it's the same engine, how many there can
be? :) but they are not the same.

What I was thinking when writing my previous email was this:

1. Named functions using global variables (both can read and modify the global variable):

$global_var = 'foo';

function named_1() {
    global $global_var;
}

function named_2() {
    global $global_var;
}



2. Closures (both lambdas can read and modify the local var)


list($closure_1, $closure_2) = call_user_func(function () {

    $local_var = 'foo';

    return array(
        function () use(& $local_var) {},
        function () use(& $local_var) {},
    );
});


As I see it right now, there's a duplication of concepts in there. The only difference is that the first example uses the global scope, while the second one uses the scope of an anonymous function.

But I admit this is just a nice-to-have thingy, not a necessity. Well, for me at least. So I won't ask for it anymore :).



** namespaced functions don't make any difference, as variables aren't
namespaced.

I'm not sure what you mean here, as variables in PHP are scoped. Global
functions are not scoped, of course, but can be namespaced.

I mean that variables declated outside of a namespaced function or class are not namespaced.

namespace foo;

$this_is_a_global_var = 'foo';

function namespaced_function() {
    global $this_is_a_globa_var;
}


--
Ionut G. Stan
I'm under construction  |  http://blog.igstan.ro/

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to