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);
   }
}
1

2 Answers 2

4
$ref = new ReflectionClass('Alpha');
var_dump($ref->getConstants());
Sign up to request clarification or add additional context in comments.

4 Comments

is ReflectionClass is inbuilt or default library in php 5+?
+1 its working perfect. i called $ref = new ReflectionClass(__CLASS__); in constructor
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
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.
2

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

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

3 Comments

That gives you all constants though, not only specific class constants.
if we call this function in Alphaclass then?
@deceze Added another link for class constants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.