0

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

2
  • with autoload like using composer, you can do this. In your demo, maybe you need require first, then use. You can use some class within same namespace. Commented Dec 14, 2020 at 9:56
  • A use statement isn't like a cd shell command. It doesn't switch current namespace, it creates an alias. Commented Dec 14, 2020 at 10:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.