3 回答
TA贡献1827条经验 获得超8个赞
您可以为此使用反射。请注意,如果您经常这样做,则可能需要查看缓存结果。
<?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'
)
TA贡献1824条经验 获得超5个赞
使用token_get_all()。即:
<?php
header('Content-Type: text/plain');
$file = file_get_contents('Profile.php');
$tokens = token_get_all($file);
$const = false;
$name = '';
$constants = array();
foreach ($tokens as $token) {
if (is_array($token)) {
if ($token[0] != T_WHITESPACE) {
if ($token[0] == T_CONST && $token[1] == 'const') {
$const = true;
$name = '';
} else if ($token[0] == T_STRING && $const) {
$const = false;
$name = $token[1];
} else if ($token[0] == T_CONSTANT_ENCAPSED_STRING && $name) {
$constants[$name] = $token[1];
$name = '';
}
}
} else if ($token != '=') {
$const = false;
$name = '';
}
}
foreach ($constants as $constant => $value) {
echo "$constant = $value\n";
}
?>
输出:
LABEL_FIRST_NAME = "First Name"
LABEL_LAST_NAME = "Last Name"
LABEL_COMPANY_NAME = "Company"
TA贡献1810条经验 获得超5个赞
使用ReflectionClass并getConstants()给出您想要的:
<?php
class Cl {
const AAA = 1;
const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());
输出:
Array
(
[AAA] => 1
[BBB] => 2
)
- 3 回答
- 0 关注
- 927 浏览
添加回答
举报