I'm implementing namespaces in my existing project. I found that you can use the keyword 'use' to import classes into your namespace. My question is, can I also import all the classes from 1 namespace into another. Example:
namespace foo
{
class bar
{
public static $a = 'foobar';
}
}
namespace
{
use \foo; //This doesn't work!
echo bar::$a;
}
Update for PHP 7+
A new feature in PHP 7 is grouped declarations. This doesn't make it as easy as using 1 'use statement' for all the classes in a given namespace, but makes it somewhat easier...
Example code:
<?php
// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
?>
See also: https://secure.php.net/manual/en/migration70.new-features.php#migration70.new-features.group-use-declarations
This is not possible in PHP.
All you can do is:
namespace Foo;
use Bar;
$obj = new Bar\SomeClassFromBar();
You can use the "as" for shortening and aliasing long namespaces
composer.json
{
"autoload": {
"psr-4": {
"Lorem\\Ipsum\\": "lorem/ipsum",
"Lorem\\Ipsum\\Dolor\\": "lorem/ipsum/dolor",
"Lorem\\Ipsum\\Dolor\\Sit\\": "lorem/ipsum/dolor/sit"
}
}
}
index.php
<?php
use Lorem\Ipsum\Dolor\Sit as FOO;
define ('BASE_PATH',dirname(__FILE__));
require BASE_PATH.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
$bar = new FOO\Bar();
$baz = new FOO\Baz();
$qux = new FOO\Qux();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With