How do I get an object#39;s unqualified (short) class name?(如何获取对象的非限定(短)类名?)
问题描述
如何在 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.)
这篇关于如何获取对象的非限定(短)类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取对象的非限定(短)类名?
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01