如何获取对象的非限定(短)类名?
如何在 PHP 名称空间环境中检查对象的类而不指定完整的命名空间类.
How do I check the class of an object within the PHP name spaced environment without specifying the full namespaced class.
例如,假设我有一个对象库/实体/合同/名称.
For example suppose I had an object library/Entity/Contract/Name.
以下代码不起作用,因为 get_class 返回完整的命名空间类.
The following code does not work as get_class returns the full namespaced class.
If(get_class($object) == 'Name') {
... do this ...
}
命名空间魔术关键字返回当前命名空间,如果测试对象有另一个命名空间,则它没有用.
The namespace magic keyword returns the current namespace, which is no use if the tested object has another namespace.
我可以简单地用命名空间指定完整的类名,但这似乎锁定了代码的结构.如果我想动态更改命名空间,也没有多大用处.
I could simply specify the full classname with namespaces, but this seems to lock in the structure of the code. Also not of much use if I wanted to change the namespace dynamically.
谁能想到一个有效的方法来做到这一点.我想一种选择是正则表达式.
Can anyone think of an efficient way to do this. I guess one option is regex.
推荐答案
你可以通过反射来做到这一点.具体来说,您可以使用 ReflectionClass::getShortName
方法,该方法获取没有其命名空间的类的名称.
You can do this with reflection. Specifically, you can use the ReflectionClass::getShortName
method, which gets the name of the class without its namespace.
首先需要构建一个ReflectionClass
实例,然后调用该实例的getShortName
方法:
First, you need to build a ReflectionClass
instance, and then call the getShortName
method of that instance:
$reflect = new ReflectionClass($object);
if ($reflect->getShortName() === 'Name') {
// do this
}
但是,我无法想象在许多情况下这是可取的.如果你想要求对象是某个类的成员,测试它的方法是使用 instanceof
.如果您想要一种更灵活的方式来表示某些约束,那么这样做的方法是编写一个接口并要求代码实现该接口.同样,正确的方法是使用 instanceof
.(您可以使用 ReflectionClass
来实现,但性能会差很多.)
However, I can't imagine many circumstances where this would be desirable. If you want to require that the object is a member of a certain class, the way to test it is with instanceof
. If you want a more flexible way to signal certain constraints, the way to do that is to write an interface and require that the code implement that interface. Again, the correct way to do this is with instanceof
. (You can do it with ReflectionClass
, but it would have much worse performance.)
相关文章