Posts Tagged ‘oop’

Iterating through class constants in PHP

Friday, June 18th, 2010

I was breaking my head trying to figure out the best way to reference a particular set of constants in one of my objects so that I didnt’t unncessarily need to create a new database table. Fortunately, I found this thread about looping through class constants using reflectors.

As a summary, it can be done in a very small amount of code:
class test{
const CONSTANT = 'foo';
}
$t = new test;
$r = new ReflectionObject($t);
print_r($r->getConstants());

With the appropriate naming convention – everything else is easy!

Thanks to jpadie.

Share on Facebook