PHP如何从另一个名称空间导入所有类

时间:2021-02-25 23:19:48

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:

我正在现有项目中实现名称空间。我发现可以使用关键字“use”将类导入到名称空间中。我的问题是,我还可以将所有类从一个名称空间导入到另一个名称空间中。例子:

namespace foo
{

    class bar
    {

        public static $a = 'foobar';

    }

}

namespace
{
    use \foo;  //This doesn't work!
    echo bar::$a;
}

Update for PHP 7+

更新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...

PHP 7中的一个新特性是分组声明。这并不像在给定的名称空间中对所有类使用1 'use statement'那么容易,但这使它更容易……

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

参见:https://secure.php.net/manual/en/migration70.new-features.php # migration70.new-features.group-use-declarations

1 个解决方案

#1


55  

This is not possible in PHP.

这在PHP中是不可能的。

All you can do is:

你所能做的就是:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();

#1


55  

This is not possible in PHP.

这在PHP中是不可能的。

All you can do is:

你所能做的就是:

namespace Foo;

use Bar;

$obj = new Bar\SomeClassFromBar();