【发布时间】:2013-11-21 02:43:26
【问题描述】:
在 PHP 中,如果我想获取包含在 use 语句中的类的完全限定类名,我该怎么做?例如,
<?php
namespace MyNamespace;
use Namespace\To\Class as MyClass;
function getNamespaceOfMyClass() {
// Return ??
}
echo getNamespaceOfMyClass();
我知道一种方法是创建get_class(new MyClass()),但如果我不能/不想创建MyClass 的实例怎么办?谢谢!
【问题讨论】:
-
你为什么要这样做?
-
@AlexP:这样做有完全正当的理由。其中之一是当您想要指示 DI 容器如何解析特定类型时。
-
@Jon 我没有说它无效。我想知道更多信息,因为这是一个人为的例子。
-
@AlexP 我的具体用例是在 Zend Framework 2 中,我们有一个 EventManager,它的事件附加到类的完全限定类名。我正在重构的代码看起来不太好——例如,它使用以下内容:
use Account\Document\Profile;,然后:get_class(new Profile());来完成这项工作,这并不理想。我想要一种普通的方式来做到这一点,最好不需要 PHP 5.5。 -
@OmarDiab 我看到了两难境地,我在尝试从
ObjectManager()->getEntityRepository($className)调用实体时遇到同样的问题,我不想对类进行硬编码。我倾向于使用在实体服务层中定义的一些静态变量(例如static::ENTITY_CLASS_NAME_PROFILE = 'Namespace/entity/Profile';
标签: php class namespaces alias