Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 763
Rob Avatar asked Aug 19 '11 12:08

Rob


2 Answers

This is not possible in PHP.

All you can do is:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();
like image 105
Ondřej Mirtes Avatar answered Sep 29 '22 19:09

Ondřej Mirtes


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();
like image 28
András Szabácsik Avatar answered Sep 29 '22 18:09

András Szabácsik