Rob
Rob

Reputation: 2666

PHP how to import all classes from another namespace

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

Upvotes: 89

Views: 63661

Answers (2)

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

Upvotes: 5

Ondřej Mirtes
Ondřej Mirtes

Reputation: 5616

This is not possible in PHP.

All you can do is:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();

Upvotes: 87

Related Questions