Для этого можно использовать Отражение . Обратите внимание, что если вы делаете это часто, вам может потребоваться кеширование результата.
<?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'
)
Используйте 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"
В PHP5 вы можете использовать Reflection: (справочник вручную)
$class = new ReflectionClass('Profile');
$consts = $class->getConstants();
Да, вы используете отражение . Посмотрите на вывод
<?
Reflection::export(new ReflectionClass('YourClass'));
?>
. Это должно дать вам представление о том, на что вы будете смотреть.
Использование ReflectionClass и getConstants ()
дает именно то, что вы хотите:
<?php
class Cl {
const AAA = 1;
const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());
Вывод:
Array
(
[AAA] => 1
[BBB] => 2
)