Importing classes and namespaces in PHP: What difference does a leading backslash make?

前端 未结 5 1127
长情又很酷
长情又很酷 2020-12-14 05:51

What\'s the difference between those two:

use Exception;
use \\Exception;

Or those:

use Foo\\Bar;
use \\Foo\\Bar;
         


        
5条回答
  •  无人及你
    2020-12-14 06:19

    Usually the leading backslash defines, that the identifier is absolute. If its missing, the interpreter assumes, that it is a relative identifier.

    This is an absolute identifier:

    $x = new \Name\Space\To\Class();
    

    This is a relative identifier, because of the no leading slash. It's relative to the current namespace:

    namespace Name\Space;
    $x = new To\Class;
    

    This is also a relative identifier. In this case, its resolved against the use statement, because the last part (alias) is the same, as the first of the class:

    namespace Other\Name\Space;
    use Name\Space;
    $x = new Space\To\Class;
    

    However, because in namespace and use statements only absolute identifiers (fully qualified names) are allowed, it's ok to omit it here. In namespace, it's even not allowed to set the leading backslash.

    For further information on how PHP resolves the different namespace declarations, see the namespace rules manual.

提交回复
热议问题