转换PHP类';常量转换为字符串


Convert PHP class' constant into string

我有一个类的常量如下:

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

有没有办法将AClass::CODE_NAME_123等常量的名称转换为字符串,例如从字符串中提取尾部数字?

您可以使用这样的东西:

//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);

您可以使用ReflectionClass::getConstants()并迭代结果以找到具有特定值的常量,然后使用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

使用ReflectionClass()并循环遍历对每个值应用preg_match的结果键,以提取字符串的最后3个数字:

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>';
}

输出为:

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