Marcel Molenaar
Marcel Molenaar

Reputation: 69

PHP namespaces, already in namespace?

I am learning PHP namespaces. There is one small piece i do not understand, example:

use Hello\Hello2;

require 'Hello/Hello2/Hello.php';

$h = new Hello2\Hello();

echo $h->sayHello();

To me, when i say: use Hello\Hello2 it seems to me i am in namespace Hello2 and so i do not understand why i have to instantiate my object like this:

$h = new Hello2\Hello();

Why not just like this (cause i am already in namespace Hello2)

$h = new Hello();

Regards,

Marcel

Upvotes: 0

Views: 55

Answers (1)

Zoli Szabó
Zoli Szabó

Reputation: 4534

It is important to understand that with these use statements you declare aliases (implicit, like in your example OR explicit).

So when you're writing

use Hello\Hello2;

you're basically writing

use Hello\Hello2 as Hello2;

As in you declare the alias Hello2 for the namespace Hello\Hello2. Think of it as a search and replace mechanism.

If you want to use directly the class name, you will have to use the fully qualified name of the class:

use Hello\Hello2\Hello;

...

new Hello();

UPDATE:

Why not just like this (cause i am already in namespace Hello2)

No, you're not in the Hello2 namespace. In order to "be" in a namespace, you have to use the namespace statement. You can be in a single namespace at a time, but you can declare multiple use statements, which again are "just" aliases (or shortcut declarations if you wish) for other namespaces, classes, functions or even constants.

More details in the PHP manual: https://www.php.net/manual/en/language.namespaces.importing.php.

Upvotes: 1

Related Questions