我在一些类上定义了几个 CONST,我想得到它们的列表。例如:
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
有什么方法可以获取在 Profile
类上定义的 CONST 的列表?据我所知,最接近的选项 (get_defined_constants()
) 无法解决问题。
我真正需要的是一个常量名称列表——像这样:
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')
最佳答案
您可以使用 Reflection为了这。请注意,如果您经常这样做,您可能需要考虑缓存结果。
<?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 - 我可以在 PHP 类上定义 CONST 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875779/