我可以在PHP类上获取CONST的定义吗?

我在某些类上定义了几个CONST,并希望获得它们的列表。例如:


class Profile {

    const LABEL_FIRST_NAME = "First Name";

    const LABEL_LAST_NAME = "Last Name";

    const LABEL_COMPANY_NAME = "Company";

}

有什么方法可以获取在Profile类中定义的CONST的列表吗?据我所知,最接近的option(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')


慕森卡
浏览 928回答 3
3回答

斯蒂芬大帝

您可以为此使用反射。请注意,如果您经常这样做,则可能需要查看缓存结果。<?phpclass Profile {&nbsp; &nbsp; const LABEL_FIRST_NAME = "First Name";&nbsp; &nbsp; const LABEL_LAST_NAME = "Last Name";&nbsp; &nbsp; const LABEL_COMPANY_NAME = "Company";}$refl = new ReflectionClass('Profile');print_r($refl->getConstants());输出:Array(&nbsp; &nbsp; 'LABEL_FIRST_NAME' => 'First Name',&nbsp; &nbsp; 'LABEL_LAST_NAME' => 'Last Name',&nbsp; &nbsp; 'LABEL_COMPANY_NAME' => 'Company')

沧海一幻觉

使用token_get_all()。即:<?phpheader('Content-Type: text/plain');$file = file_get_contents('Profile.php');$tokens = token_get_all($file);$const = false;$name = '';$constants = array();foreach ($tokens as $token) {&nbsp; &nbsp; if (is_array($token)) {&nbsp; &nbsp; &nbsp; &nbsp; if ($token[0] != T_WHITESPACE) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($token[0] == T_CONST && $token[1] == 'const') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $const = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $name = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if ($token[0] == T_STRING && $const) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $const = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $name = $token[1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if ($token[0] == T_CONSTANT_ENCAPSED_STRING && $name) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $constants[$name] = $token[1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $name = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if ($token != '=') {&nbsp; &nbsp; &nbsp; &nbsp; $const = false;&nbsp; &nbsp; &nbsp; &nbsp; $name = '';&nbsp; &nbsp; }}foreach ($constants as $constant => $value) {&nbsp; &nbsp; echo "$constant = $value\n";}?>输出:LABEL_FIRST_NAME = "First Name"LABEL_LAST_NAME = "Last Name"LABEL_COMPANY_NAME = "Company"

森栏

使用ReflectionClass并getConstants()给出您想要的:<?phpclass Cl {&nbsp; &nbsp; const AAA = 1;&nbsp; &nbsp; const BBB = 2;}$r = new ReflectionClass('Cl');print_r($r->getConstants());输出:Array(&nbsp; &nbsp; [AAA] => 1&nbsp; &nbsp; [BBB] => 2)
打开App,查看更多内容
随时随地看视频慕课网APP