转换PHP类'常量为字符串

时间:2013-12-04 15:34:06

标签: php reflection constants

我有一个像这样的常量类:

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

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

3 个答案:

答案 0 :(得分:4)

您可以使用以下内容:

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

答案 1 :(得分:1)

您可以使用ReflectionClass::getConstants()并遍历结果以查找具有特定值的常量,然后使用正则表达式从常量名称中获取最后一位数字:

<?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

答案 2 :(得分:0)

使用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
)
相关问题