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
Xmlparseentityref: No Name' Warnings While Loading Xml into a PHP File
Get the Last Modified Date of a Remote File
Parsing JSON Array with PHP Foreach
Multiple Index Variables in PHP Foreach Loop
PHP Get Index of Last Inserted Item in Array
Which Line Break in PHP Mail Header, \R\N or \N
How to Make a Bbcode to Parse Url Tags into Links
How to Access an Application Parameters from a Service
Long Polling/Http Streaming General Questions
Check If Site Is Inside Iframe
How to Pass Parameters by Reference Using Call_User_Func_Array()
How to Create a Subquery Using Laravel Eloquent
How to Regex-Replace Multiple <Br /> Tags with One <Br /> Tag