PHP how to import all classes from another namespace

PhpImportNamespaces

Php Problem Overview


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

Php Solutions


Solution 1 - Php

This is not possible in PHP.

All you can do is:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();

Solution 2 - Php

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobView Question on Stackoverflow
Solution 1 - PhpOndřej MirtesView Answer on Stackoverflow
Solution 2 - PhpAndrás SzabácsikView Answer on Stackoverflow