0

I have a bunch of classes in my root namespace. I want to use them in another namespace but I can't figure out how to "include" them so that I don't have to add the backslash in the beginning.

class A {
    public static $a = 1;
}

namespace B {
    use \; // apparently invalid 

    class C {
        static function D { return A::$a; } // desired syntax
    }
}

\B\C::D(); // expected result is 1

Is this possible?

1
  • see this section of the manual Commented Mar 24, 2015 at 14:31

2 Answers 2

2

Regardless of whether the namespace is "root" or not, you cannot import an entire namespace using use. The best you can do is:

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

4 Comments

That is not true, I can almost bet I've seen imported namespaces in laravel
use is just aliasing names to other names. Yes, you can certainly alias a namespace, like use Foo\Bar, which is short for use Foo\Bar as Bar. However, you still have to write Bar\Baz, you can't just write Baz to use \Foo\Bar\Baz. I'm saying you cannot alias all classes in a namespace with just one use statement.
Oh well, it would be so awesome if I could.
That's unfortunately simply not how PHP works. Namespaces are just a layer on top of symbols (class names and such). A namespace cannot know all the classes that are in it, because PHP typically (auto)loads classes when they're first used, not when you write the use statement. PHP's namespaces are not a module import system.
-1

Change your use statement to

use \A -

And then you'll get your desired syntax -

2 Comments

Yeah I figured I'd get answers like that so I mentioned "a bunch of classes".
The leading \ is superfluous. It's just use A.

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.