Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use multiple classes in other namespaces

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.

like image 709
xdevel2000 Avatar asked Apr 09 '10 11:04

xdevel2000


People also ask

Can you have multiple classes in a namespace?

Two classes with the same name can be created inside 2 different namespaces in a single program. Inside a namespace, no two classes can have the same name.

What is the correct way to import multiple classes from the same namespace in a single declaration?

From PHP7 onwards, a single use statement can be used to import Classes, functions and constants from same namespace instead of multiple use statements.

Can you have multiple classes C#?

But C# does not support multiple class inheritance. To overcome this problem we use interfaces to achieve multiple class inheritance.

Can we declare multiple namespaces in same file?

Defining multiple namespaces in the same file ¶Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.


3 Answers

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;
like image 139
Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ Avatar answered Sep 22 '22 22:09

Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ


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.

like image 21
Gordon Avatar answered Sep 26 '22 22:09

Gordon


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
like image 34
Kamil Szot Avatar answered Sep 24 '22 22:09

Kamil Szot