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

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

    The manual specifies the backslash as unnecessary, which naturally means that if you still use it that the meaning is equivalent. However, as you have pointed out, the manual says that it is supposedly not allowed, which is false.

    However, there is something else troubling with the manual. They advertise this:

    // importing a global class
    use \ArrayObject;
    

    If it is true that import names are not processed relative to the current namespace, then use \ArrayObject and use ArrayObject must have the same meaning. What else could use ArrayObject refer to other than the global one? In practice, the engine will import the global one.

    Also, with bugs such as this: http://bugs.php.net/bug.php?id=49143

    I believe there is confusion over what the standard is supposed to be.

    To answer your question: there is no difference. However, if I was the engine developer who was also a believer of the no-leading-slash standard, then I wouldn't need to consider a case where someone wrote use \Exception;. I believe this was likely the case.

提交回复
热议问题