我可以在PHP类上获取CONST的定义吗? [英] Can I get CONST's defined on a PHP class?
本文介绍了我可以在PHP类上获取CONST的定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在某些类上定义了几个CONST,并希望获得它们的列表.例如:
I have several CONST's defined on some classes, and want to get a list of them. For example:
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
是否有任何方法可以获取在Profile
类上定义的CONST的列表?据我所知,最接近的选项(get_defined_constants()
)不会解决问题.
Is there any way to get a list of the CONST's defined on the Profile
class? As far as I can tell, the closest option(get_defined_constants()
) won't do the trick.
我真正需要的是一个常量名称列表-像这样:
What I actually need is a list of the constant names - something like this:
array('LABEL_FIRST_NAME',
'LABEL_LAST_NAME',
'LABEL_COMPANY_NAME')
或者:
array('Profile::LABEL_FIRST_NAME',
'Profile::LABEL_LAST_NAME',
'Profile::LABEL_COMPANY_NAME')
甚至:
array('Profile::LABEL_FIRST_NAME'=>'First Name',
'Profile::LABEL_LAST_NAME'=>'Last Name',
'Profile::LABEL_COMPANY_NAME'=>'Company')
推荐答案
您可以使用反射.请注意,如果您经常这样做,则可能需要查看缓存结果.
You can use Reflection for this. Note that if you are doing this a lot you may want to looking at caching the result.
<?php
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());
输出:
Array
(
'LABEL_FIRST_NAME' => 'First Name',
'LABEL_LAST_NAME' => 'Last Name',
'LABEL_COMPANY_NAME' => 'Company'
)
这篇关于我可以在PHP类上获取CONST的定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文