Question

I'm trying to figure out how namespaces work in PHP but have a hard time understanding when a global namespace prefix is required. Take the following example:

index.php

namespace MySpace;

require_once 'file.php';

Test::hello();

hi();

file.php

class Test {
    public static function hello () {
        echo 'hello';
    }
}

function hi() {
    echo 'hi';
}

This won't work but writing \Test::hello() instead will and echoes both "hello" and "hi".

Why isn't the \ required for hi() as well?

Was it helpful?

Solution

http://php.net/manual/en/language.namespaces.fallback.php

Using namespaces: fallback to global function/constant

Inside a namespace, when PHP encounters an unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, one must refer to them with their fully qualified Name [...]

For functions and constants, PHP will fall back to global functions or constants if a namespaces function or constant does not exist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top