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:

<?php 

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:

<?php
$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:

<?php
$sPrefix = 'IAM_A_CLASS::IAM_A_CONSTANT_';
for($i=3; $i > 0; $i--){
    echo constant($sPrefix . $i) . "\n";
}

The result is:

3
2
1

So yes, it is possible.

Further information about the constant command:

Can be found under http://php.net/manual/de/function.constant.php.

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.