Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected namespace behavior with closures

Using PHP 7.0, consider the code below:

<?php
namespace A {
    $closure = function() {
        echo __NAMESPACE__;
    };
}
namespace B {
    $closure = function () {
        echo __NAMESPACE__;
    };
}
namespace C {
    $closure();
}

To me, the expected output would be:

PHP Notice:  Undefined variable: closure

But somehow the result is

B

Then consider this code below:

<?php
namespace A {
    $closure = function() {
        echo __NAMESPACE__;
    };
}
namespace B {
    $closure = function () {
        echo __NAMESPACE__;
    };
}
namespace C {
    \A\$closure();
}

Now knowing (but not yet understanding) the behavior of the first example the expected output to me would be:

A

But instead I get

PHP Parse error:  syntax error, unexpected '$closure' (T_VARIABLE), expecting identifier (T_STRING)

This behavior completely confuses me.

Question part 1: can someone explain me what is wrong with my expectation in the first example? Question part 2: how is the behavior consistent with the first example?

like image 906
Hakariki Avatar asked Mar 06 '23 02:03

Hakariki


1 Answers

The behavior you observed should not confuse you. It is what supposed to happen. It is exactly how PHP namespace works.

PHP manual explains:

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

Not variables.

This means that $closure in your code is the exact same variable in all the namespaces you defined (A, B and C). It is first defined in namespace A. Then the value is replaced in namespace B. Then you call the closure it contains in namespace C.

The second example is the same. Because namespaces are not for grouping variables, it should be obvious that \A\$closure() is an invalid syntax.

like image 141
Rei Avatar answered Mar 07 '23 17:03

Rei