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

前端 未结 5 1129
长情又很酷
长情又很酷 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:13

    le't say we have

    namespace MyNamespace
    use Exception;
    use \Exception;
    

    then the first use actually imports class MyNamespace\Exception and the second one just the main class \Exception

    so you can have something like

    namespace MyNamespace;
    class Exception extends \Exception{ }
    

    and then I can

    throw new \Exception('Exception from global namespace');
    throw new \MyNamespace\Exception('Exception from MyNamespace');
    

提交回复
热议问题