2015-12-27 130 views
8

實例類的數組:獲取類的靜態成員變量

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辦法讓類的靜態成員變量的數組沒有在本例中創建它手動什麼樣的?

回答

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