문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top