0

I'm writing classes in PHP in deep namespace, but I want it to be easier to access. Is there a way to alias namespace within it's definition, not import? It's okay if it's work-around.

I want to achieve it, becouse its very, very commonly used class in code I have on hands, but moving it into more shallow namespace entirely is not an option.

I've tried to google it but all I found was import namespace aliasing, I havent found anything revelant also anything in docs.

Definition file:

namespace \Something\Really\Annoyingly\Deep AS \MyClass

class MyClass{}

Other file:

namespace \Something\Else;

use MyClass;

$obj = new MyClass();

I used "AS" here for sake of example. I know it will not work, and my question is, is it possible to make it work somehow?

3
  • You do not need to import within the current namespace. I am not sure I understand your question. Commented Sep 12, 2019 at 10:03
  • 1
    Namespaces are like packages which a list of classes, interfaces etc under a particular jurisdiction. If you could alias it, then don't provide a namespace in the first place. Another reason is you could very easily alias 2 namespaces with the same name. So now PHP doesn't know which one you are referring to. Commented Sep 12, 2019 at 10:07
  • So, if you could alias at definition time… the class would be accessible as \MyClass… Well, you can do this by omitting the namespace entirely. What's the point? Commented Sep 12, 2019 at 12:45

1 Answer 1

1

No, it's not possible.

The aliases can only be declared at import time, and are file-based.

If you think about it, you'll realize it doesn't make sense it were possible. There is nothing to be gained and a lot to be able to be broken if this was possible.

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

1 Comment

Well, I hoped community can prove me wrong and tell me there is a way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.