2010-10-04 58 views
1

我想從類中獲取所有非靜態類變量。我遇到的問題是在「非靜態」部分。以下內容:如何查找所有非靜態類屬性

foreach(array_keys(get_class_vars(get_called_class())) AS $key) { 
    echo $key; 
} 

如何找到$ key是靜態屬性還是非靜態屬性?我知道我可以嘗試這樣的:

@$this->$key 

但是,一定有更好的方法來檢查這一點。

有人嗎?

+4

http://php.net/manual/en/class.reflectionclass.php – user187291 2010-10-04 14:35:57

回答

4

這段代碼是我的解決方案。

$ReflectionClass = new \ReflectionClass(get_called_class()); 

$staticAttributes = $ReflectionClass->getStaticProperties(); 
$allAttributes = $ReflectionClass->getProperties(); 

$attributes = array_diff($staticAttributes, $allAttributes); 
1
class testClass 
{ 
    private static $staticValPrivate; 

    protected static $staticValProtected; 

    public static $staticValPublic; 

    private $valPrivate; 

    protected $valProtected; 

    public $valPublic; 

    public function getClassProperties() 
    { 
     return get_class_vars(__CLASS__); 
    } 

    public function getAllProperties() 
    { 
     return get_object_vars($this); 
    } 

} 

$x = new testClass(); 

var_dump($x->getClassProperties()); 
echo '<br />'; 

var_dump($x->getAllProperties()); 
echo '<br />'; 

var_dump(array_diff_key($x->getClassProperties(),$x->getAllProperties()));