PHP How to Import All Classes from Another Namespace

PHP how to import all classes from another namespace

This is not possible in PHP.

All you can do is:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();

Import class from another namespace dynamically

you may do this as follows:

namespace Foo;

$class = 'SomeClassFromBar';

$stdClass = "\\Bar\\" . $class;

$obj = new $stdClass();

full example :

namespace Bar {
class SomeClassFromBar
{
public function __construct()
{
echo __CLASS__ . "\n";
}
}
}

namespace Foo {
$class = 'SomeClassFromBar';

$stdClass = "\\Bar\\" . $class;

$obj = new $stdClass();

// Output : Bar\SomeClassFromBar
}

Import everything from a namespace

In PHP you do not "import from" a namespace. You can only alias a namespace or class to another (presumably shorter) name. So typically you do this:

use Foo as F;

new F\Bar;

That's the PHP "equivalent" to "using everything from a namespace as conveniently as possible".

Import namespace in PHP

use namespaceproj\lib1 ;

Here you are importing the namespace, not all of the classes inside of that namespace. Therefore, you're trying to create a symbol lib1 pointing towards the namespace namespaceproj\lib1. This fails because you already have a lib1 symbol as a class.

use namespaceproj\lib1  as libnew;

Again, namespaceproj\lib1 is a namespace, not a class. So now you have a symbol named libnew for the namespace and you can instantiate classes using this aliased namespace:

new libnew\lib1;

PHP7 introduced group import syntax, but it still requires you to declare which classes you are importing.

use some\namespace\{ClassA, ClassB, ClassC}

Use multiple classes in other namespaces

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.



Related Topics



Leave a reply



Submit