Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

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

What's the difference between those two:

use Exception;
use Exception;

Or those:

use FooBar;
use FooBar;

The manual says:

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as FooBar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not allowed, as import names must be fully qualified, and are not processed relative to the current namespace.

But I don't really understand this, as all of the above variants work, i.e. it definitely is not "not allowed".

A look into zend_do_use showed, that is_global (set, when there is a leading backslash) is only used for a warning in the following case:

namespace {
    use Exception;
}

Which tells me: "The use statement with non-compound name 'Exception' has no effect". (Though doing the same with use Exception would have just as little effect, but does not throw a warning.)

So: Am I missing something? Is there actually some difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...