代码之家  ›  专栏  ›  技术社区  ›  user243901

获取类常量列表[重复]

php
  •  3
  • user243901  · 技术社区  · 14 年前

    我在一些类上定义了几个常量,并希望得到它们的列表。例如:

    class Profile {
        const LABEL_FIRST_NAME = "First Name";
        const LABEL_LAST_NAME = "Last Name";
        const LABEL_COMPANY_NAME = "Company";
    }
    

    是否有任何方法可以获取在 Profile 上课?据我所知,最近的选择( get_defined_constants() )不会成功的。

    我实际需要的是一个常量名列表-类似于:

    array('LABEL_FIRST_NAME',
        'LABEL_LAST_NAME',
        'LABEL_COMPANY_NAME')
    

    或:

    array('Profile::LABEL_FIRST_NAME', 
        'Profile::LABEL_LAST_NAME',
        'Profile::LABEL_COMPANY_NAME')
    

    甚至:

    array('Profile::LABEL_FIRST_NAME'=>'First Name', 
        'Profile::LABEL_LAST_NAME'=>'Last Name',
        'Profile::LABEL_COMPANY_NAME'=>'Company')
    
    0 回复  |  直到 6 年前
        1
  •  221
  •   datashaman    6 年前

    你可以用 Reflection 为了这个。请注意,如果您经常这样做,您可能希望看到缓存结果。

    <?php
    class Profile {
        const LABEL_FIRST_NAME = "First Name";
        const LABEL_LAST_NAME = "Last Name";
        const LABEL_COMPANY_NAME = "Company";
    }
    
    
    $refl = new ReflectionClass('Profile');
    print_r($refl->getConstants());
    

    输出:

    Array
    (
        'LABEL_FIRST_NAME' => 'First Name',
        'LABEL_LAST_NAME' => 'Last Name',
        'LABEL_COMPANY_NAME' => 'Company'
    )
    
        2
  •  21
  •   Wrikken    14 年前

    This

     $reflector = new ReflectionClass('Status');
     var_dump($reflector->getConstants());
    
        3
  •  15
  •   cletus    16 年前

    使用 token_get_all() . 即:

    <?php
    header('Content-Type: text/plain');
    
    $file = file_get_contents('Profile.php');
    $tokens = token_get_all($file);
    
    $const = false;
    $name = '';
    $constants = array();
    foreach ($tokens as $token) {
        if (is_array($token)) {
            if ($token[0] != T_WHITESPACE) {
                if ($token[0] == T_CONST && $token[1] == 'const') {
                    $const = true;
                    $name = '';
                } else if ($token[0] == T_STRING && $const) {
                    $const = false;
                    $name = $token[1];
                } else if ($token[0] == T_CONSTANT_ENCAPSED_STRING && $name) {
                    $constants[$name] = $token[1];
                    $name = '';
                }
            }
        } else if ($token != '=') {
            $const = false;
            $name = '';
        }
    }
    
    foreach ($constants as $constant => $value) {
        echo "$constant = $value\n";
    }
    ?>
    

    输出:

    LABEL_FIRST_NAME = "First Name"
    LABEL_LAST_NAME = "Last Name"
    LABEL_COMPANY_NAME = "Company"
    
        4
  •  13
  •   SeanCannon    13 年前

    根据php-docs注释,如果您能够使用ReflectionClass(php 5):

    function GetClassConstants($sClassName) {
        $oClass = new ReflectionClass($sClassName);
        return $oClass->getConstants();
    }
    

    Source is here.

        5
  •  13
  •   OzzyCzech    13 年前

    在php5中,您可以使用反射: (manual reference)

    $class = new ReflectionClass('Profile');
    $consts = $class->getConstants();
    
        6
  •  8
  •   Ben James    15 年前

    使用ReflectionClass和 getConstants() 给出你想要的:

    <?php
    class Cl {
        const AAA = 1;
        const BBB = 2;
    }
    $r = new ReflectionClass('Cl');
    print_r($r->getConstants());
    

    输出:

    Array
    (
        [AAA] => 1
        [BBB] => 2
    )
    
        7
  •  5
  •   chaos    16 年前

    是的,你用 reflection . 查看的输出

    <?
    Reflection::export(new ReflectionClass('YourClass'));
    ?>
    

    这应该让你知道你会看到什么。

        8
  •  4
  •   Saic Siquot    10 年前

    在类中有一个方法返回自己的常量很方便。
    你可以这样做:

    class Profile {
        const LABEL_FIRST_NAME = "First Name";
        const LABEL_LAST_NAME = "Last Name";
        const LABEL_COMPANY_NAME = "Company";
    
    
        public static function getAllConsts() {
            return (new ReflectionClass(get_class()))->getConstants();
        }
    }
    
    // test
    print_r(Profile::getAllConsts());
    
        9
  •  4
  •   Antoine DevWL    7 年前

    采用静态方法的特性-用于救援

    看起来它是一个使用带有静态函数的特性来扩展类功能的好地方。traits还允许我们在任何其他类中实现这个功能,而无需反复重写相同的代码(保持干燥)。

    在profile类中使用自定义的“constantexport”特性。对于您需要这个功能的每个类都这样做。

    /**
     * ConstantExport Trait implements getConstants() method which allows 
     * to return class constant as an assosiative array
     */
    Trait ConstantExport 
    {
        /**
         * @return [const_name => 'value', ...]
         */
        static function getConstants(){
            $refl = new \ReflectionClass(__CLASS__);
            return $refl->getConstants();
        }
    }
    
    Class Profile 
    {
        const LABEL_FIRST_NAME = "First Name";
        const LABEL_LAST_NAME = "Last Name";
        const LABEL_COMPANY_NAME = "Company";
    
        use ConstantExport;
    
    }
    

    使用示例

    // So simple and so clean
    $constList = Profile::getConstants(); 
    
    print_r($constList); // TEST
    

    输出:

    Array
    (
        [LABEL_FIRST_NAME] => First Name
        [LABEL_LAST_NAME] => Last Name
        [LABEL_COMPANY_NAME] => Company
    )
    
        10
  •  3
  •   Detect    14 年前

    为什么不把它们作为数组放在类变量中?使循环更容易。

    private $_data = array("production"=>0 ...);
    
        11
  •  3
  •   revoke    12 年前

    最终使用名称空间:

    namespaces enums;
    class enumCountries 
    {
      const CountryAustria          = 1 ;
      const CountrySweden           = 24;
      const CountryUnitedKingdom    = 25;
    }
    

    namespace Helpers;
    class Helpers
    {
      static function getCountries()
      {
        $c = new \ReflectionClass('\enums\enumCountries');
        return $c->getConstants();
      }
    }
    

    print_r(\Helpers\Helpers::getCountries());
    
        12
  •  1
  •   Юрий Светлов    6 年前
    Class Qwerty 
    {
        const __COOKIE_LANG_NAME__ = "zxc";
        const __UPDATE_COOKIE__ = 30000;
    
        // [1]
        public function getConstants_(){
    
            return ['__COOKIE_LANG_NAME__' => self::__COOKIE_LANG_NAME__, 
                    '__UPDATE_COOKIE__' => self::__UPDATE_COOKIE__]; 
        }    
    
        // [2]
        static function getConstantsStatic_(){
    
            return ['__COOKIE_LANG_NAME__' => self::__COOKIE_LANG_NAME__, 
                    '__UPDATE_COOKIE__' => self::__UPDATE_COOKIE__]; 
        } 
    }
    

    // [1]
    $objC = new Qwerty();
    var_dump($objC->getConstants_());
    
    // [2]
    var_dump(Qwerty::getConstantsStatic_());
    
    推荐文章