2012-02-27 29 views
0

我試圖從靜態方法中獲取類常量列表。PHP:從靜態方法使用ReflectionClass獲取類常量

public static function example() 
{ 
    $reflection = new \ReflectionClass(get_called_class()); 
    var_dump($reflection -> getConstants()); 
} 

拋出Fatal error: Cannot access self:: when no class scope is active

有什麼辦法這個工作,還是我起來反對在PHP另一種語言的限制?

回答

0

我剛剛試過你的代碼,它能正常工作,你可以提供一個你的實際類的例子嗎?

class test23 { 
    const te = 'asd'; 
    var $ya = 'hoopla'; 
    public static function example() 
    { 
     $reflection = new ReflectionClass(get_called_class()); 
     var_dump($reflection -> getConstants()); 
    } 
} 

test23::example();回報array(1) { ["te"]=> string(3) "asd" }

-2
// creates a reflection class object 
$reflection = new ReflectionClass ($this); 

//gets all the constants of the current class 
$consts = $reflection->getConstants(); 

希望它幫助。