21

If I have some php classes inside a namespace com\test

and want to import all of them into another php file how can do that?

use com\test\ClassA use com\test\ClassB ... 

use com\test\* give me syntax error.

3 Answers 3

34

From PHP 7.0 onwards, classes, functions, and constants being imported from the same namespace can be grouped together in a single use statement.

Like this way:

use com\test\{ClassA, ClassB}; $a = new ClassA; $b = new ClassB; 

Read more here: PHP Manual for Aliasing/Importing

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

Comments

7

This should work:

use com\test; $a = new \test\ClassA; $b = new \test\ClassB; 

or

use com\test\ClassA as ClassA; use com\test\ClassB as ClassB; $a = new ClassA; $b = new ClassB; 

See the PHP manual on Using namespaces: Aliasing/Importing.

4 Comments

Very boring! Hope PHP developers will put that feature.
Agreed. I realize that it is to prevent naming collisions but honestly - .NET, Java, and others have been doing it for years. Is is it so hard to throw a fatal error instead of forcing us to have ugly syntax?
the first example would be referring to classes in the namespace test not com\test, you would have to remove the beginning "\" for it to be using the alias test
@lagbox is right, the beginning "\" for the alias new test\ClassA and test\ClassB will give Fatal error.
2

I think you can't do such thing.

You can do:

 use com\test 

and refer to your classes at later time as:

test\ClassA test\ClassB 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.