tags:

views:

46

answers:

3

Is it possible to fetch all defined constants from class ? I.e. I have following class:

class Cl {
    const AAA = 1;
    const BBB = 2;
}

and I would like to get an array:

array (
    'AAA' => 1,
    'BBB' => 2,
)
+1  A: 

Using Reflection, and a ReflectionClass on Cl, you can use the function getConstants

http://nz.php.net/manual/en/class.reflectionclass.php

Tim
+2  A: 

Using ReflectionClass and getConstants() gives exactly what you want:

<?php
class Cl {
    const AAA = 1;
    const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());

Output:

Array
(
    [AAA] => 1
    [BBB] => 2
)
Ben James
+1  A: 

Reflection will be your savior.

Björn