Get constant value by generated name

Today a colleague of mine ask me if it is possible to call a class constant inside of another class by generating the constant name on the fly. The reason was, that he had multiple constants in one class that had patterned / generic names like that:


class IAM_A_CLASS{
    const IAM_A_CONSTANT_1 = 1;
    const IAM_A_CONSTANT_2 = 2;
    const IAM_A_CONSTANT_3 = 3;

And he wanted to address them like that:

$iNumber = 1; // or 2 or 3
$sConstName = IAM_A_CLASS::IAM_A_CONSTANT_.$iNumber;
var_dump($sConstName); // => should be resolved to 1,2 and 3

And, what should I tell you?   PHP hast such great functionality! 😉 The constant command:

for($i=3; $i > 0; $i--){
    echo constant($sPrefix . $i) . "\n";

The result is:


So yes, it is possible.

Further information about the constant command:

Can be found under

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.