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
1.2k views
in Technique[技术] by (71.8m points)

oop - How to use objects from other namespaces and how to import namespaces in PHP

What is the main difference between these two lines?:

$obj = new ArrayObject();

&

$obj = new ArrayObject();

When I used the first line I got an error: "Fatal error: Class 'FooBarArrayObject' not found..." and I am not too sure as to why I got this error? The second line seemed to have fixed the problem.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If you use:

$obj = new ArrayObject();

it means that ArrayObject is defined in current namespace. You can use this syntax where you are in global namespace (no namespace defined in current scope) or if ArrayObject is defined in the same namespace as current scope (example FooBar).

And if you use:

$obj = new ArrayObject();

it means that ArrayObject is defined in global namespace.

In your example you probably have code something like that:

namespace FooBar;

$obj = new ArrayObject();

It won't work because you haven't defined ArrayObject in FooBar namespace.

The above code is the same as:

namespace FooBar;

$obj = new FooBarArrayObject();

And if ArrayObject is defined in global namespace (as probably in your case) you need to use code:

namespace FooBar;

$obj = new ArrayObject();

to accent that ArrayObject is not defined in FooBar namespace;

One more thing - if you use ArrayObject in many places in your current namespace it might be not very convenient to add each time leading backslash. That's why you may import namespace so you could use easier syntax:

namespace FooBar;

use ArrayObject;

$obj = new ArrayObject();

As you see use ArrayObject; was added before creating object to import ArrayObject from global namespace. Using use you don't need to add (and you shouldn't) add leading backslash however it works the same as it were use ArrayObject; so above code is equivalent logically to:

namespace FooBar;

use ArrayObject;

$obj = new ArrayObject();

however as I said leading backslash in importing namespaces should not be used. Quoting PHP manual for that:

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 recommended, as import names must be fully qualified, and are not processed relative to the current namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...