4

I was working with a class where almost 20 constant are defined, as i want all these constant value in an array, i just want to know

is there any method which create an array of all constant of a class?

I tried with compact BUT it does not work with constants.

class Alpha
{
 const ONE = 'fixone'; 
 const TWO = 'fix_two';
 const THREE = 3     

   public function __construct()
   {
     protected $arr_constant = compact(ONE,TWO,THREE); // gives FATAL Error
     // is there any method which collect all consant and create an array?
     protected $arr_contact = get_all_constant(__CLASS__); 
     var_dump($arr_constant);
   }
}
j0k
  • 22,600
  • 28
  • 79
  • 90
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • possible duplicate of [Can I get CONST's defined on a PHP class?](http://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class) – deceze Aug 29 '12 at 09:55

2 Answers2

4
$ref = new ReflectionClass('Alpha');
var_dump($ref->getConstants());
deceze
  • 510,633
  • 85
  • 743
  • 889
  • is `ReflectionClass` is inbuilt or default library in php 5+? – xkeshav Aug 29 '12 at 09:43
  • +1 its working perfect. i called `$ref = new ReflectionClass(__CLASS__);` in constructor – xkeshav Aug 29 '12 at 10:09
  • its is mentioned on documents that **This function is currently not documented; only its argument list is available.** May I use this in live project or is there any chances of depreciation – xkeshav Aug 29 '12 at 10:10
  • 1
    It's been there for quite a while and deprecation would make little sense, since it's useful and there's no replacement I know of. So yes, it's fine to use. It's simply not well documented, since it's something of a meta-function, the naming is pretty self-explanatory and if you're using it you should know what you're doing. – deceze Aug 29 '12 at 10:15
2

Use: http://php.net/manual/en/function.get-defined-constants.php

And: http://php.net/manual/en/reflectionclass.getconstants.php

Ariel
  • 25,995
  • 5
  • 59
  • 69