20

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.

Kerem
  • 11,377
  • 5
  • 59
  • 58
xdevel2000
  • 20,780
  • 41
  • 129
  • 196

3 Answers3

32

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

Abraham
  • 8,525
  • 5
  • 47
  • 53
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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 11
    Very boring! Hope PHP developers will put that feature. – xdevel2000 Apr 09 '10 at 11:59
  • 1
    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? – Jarrod Nettles Jan 06 '11 at 16:34
  • 1
    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 Jan 20 '22 at 00:01
  • @lagbox is right, the beginning "\" for the alias new test\ClassA and test\ClassB will give Fatal error. – Muhammad Zohaib Mar 15 '23 at 16:58
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
Kamil Szot
  • 17,436
  • 6
  • 62
  • 65