Desmond Hume
Desmond Hume

Reputation: 8617

Convert PHP class' constant into string

I have a class with constants like this:

class AClass
{
    const CODE_NAME_123 = "value1";
    const CODE_NAME_456 = "value2";
}

Is there a way to convert the name of a constant like AClass::CODE_NAME_123 into a string in order to, e.g., extract the trailing digits from the string?

Upvotes: 1

Views: 2177

Answers (3)

user399666
user399666

Reputation: 19889

You can use something like this:

//PHP's ReflectionClass will allow us to get the details of a particular class
$r = new ReflectionClass('AClass');
$constants = $r->getConstants();

//all constants are now stored in an array called $constants
var_dump($constants);

//example showing how to get trailing digits from constant names
$digits = array();
foreach($constants as $constantName => $constantValue){
    $exploded = explode("_", $constantName);
    $digits[] = $exploded[2];
}

var_dump($digits);

Upvotes: 4

h2ooooooo
h2ooooooo

Reputation: 39540

You can use ReflectionClass::getConstants() and iterate through the result to find a constant with a specific value, and then get the last digits from the constant name with regex:

<?php
    class AClass
    {
        const CODE_NAME_123 = "foo";
        const CODE_NAME_456 = "bar";
    }
    
    function findConstantWithValue($class, $searchValue) {
        $reflectionClass = new ReflectionClass($class);
        foreach ($reflectionClass->getConstants() as $constant => $value) {
            if ($value === $searchValue) {
                return $constant;
            }
        }
        return null;
    }
    
    function findConstantDigitsWithValue($class, $searchValue) {
        $constant = findConstantWithValue($class, $searchValue);
        if ($constant !== null && preg_match('/\d+$/', $constant, $matches)) {
            return $matches[0];
        }
        return null;
    }
    
    var_dump( findConstantDigitsWithValue('AClass', 'foo') ); //string(3) "123"
    var_dump( findConstantDigitsWithValue('AClass', 'bar') ); //string(3) "456"
    var_dump( findConstantDigitsWithValue('AClass', 'nop') ); //NULL
?>

DEMO

Upvotes: 1

Giacomo1968
Giacomo1968

Reputation: 26076

Use ReflectionClass() and loop through the resulting keys applying a preg_match to each value to extract the last 3 numbers of the string:

class AClass
{
    const CODE_NAME_123 = "";
    const CODE_NAME_456 = "";
}

$constants = new ReflectionClass('AClass');

$constants_array = $constants->getConstants();

foreach ($constants_array as $constant_key => $constant_value) {
   preg_match('/\d{3}$/i', $constant_key, $matches);
   echo '<pre>';
   print_r($matches);
   echo '</pre>';
}

The output would be:

Array
(
    [0] => 123
)
Array
(
    [0] => 456
)

Upvotes: 0

Related Questions