获取类静态成员变量的数组

时间:2015-12-27 13:00:59

标签: php

示例类:

class Example{
   public static $ONE = [1,'one'];
   public static $TWO = [2,'two'];
   public static $THREE = [3,'three'];

   public static function test(){

       // manually created array 
       $arr = [
           self::$ONE,
           self::$TWO,
           self::$THREE
       ];
   }       
}

在PHP中是否有办法获取类静态成员变量数组,而无需像示例中那样手动创建它?

1 个答案:

答案 0 :(得分:10)

是的,有:

使用ReflectiongetStaticProperties()方法

class Example{
   public static $ONE = [1,'one'];
   public static $TWO = [2,'two'];
   public static $THREE = [3,'three'];

   public static function test(){
        $reflection = new ReflectionClass(get_class()); 
        return $reflection->getStaticProperties();
    }       
}

var_dump(Example::test());

Demo