如何获取对象的不合格(短)类名? [英] How do I get an object's unqualified (short) class name?

查看:150
本文介绍了如何获取对象的不合格(短)类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在PHP名称隔开的环境中检查对象的类,而不指定完整的命名空间类。

How do I check the class of an object within the PHP name spaced environment without specifying the full namespaced class.

例如假设我有一个对象库/ Entity / Contract / Name。

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 ...
}

namespace magic关键字返回当前命名空间,对象有另一个命名空间。

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.)

这篇关于如何获取对象的不合格(短)类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆