2015-12-27 18 views
8

Ví dụ lớp:Nhận một mảng của lớp biến thành viên tĩnh

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

Có cách nào trong PHP để có được một mảng của các biến thành viên tĩnh lớp mà không cần tạo nó bằng tay như trong ví dụ?

Trả lời

10

Có có:

Sử dụng Reflection, và getStaticProperties() phương pháp

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

Các vấn đề liên quan