php PHP如何从另一个命名空间导入所有类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP how to import all classes from another namespace
提问by Rob
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”将类导入到您的命名空间中。我的问题是,我还可以将 1 个命名空间中的所有类导入到另一个命名空间中吗?例子:
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 语句”那样简单,但使它更容易一些......
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};
?>
另见:https: //secure.php.net/manual/en/migration70.new-features.php#migration70.new-features.group-use-declarations
采纳答案by Ond?ej Mirtes
This is not possible in PHP.
这在 PHP 中是不可能的。
All you can do is:
你所能做的就是:
namespace Foo;
use Bar;
$obj = new Bar\SomeClassFromBar();
回答by András Szabácsik
You can use the "as" for shortening and aliasing long namespaces
您可以使用“as”来缩短和别名长命名空间
composer.json
作曲家.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
<?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();