2014-04-10 214 views
1

我試圖使用反射來獲取類的所有屬性,但是一些屬性仍然是搞亂的。類反射:缺少屬性

這裏所以在這一點上我$測試對象有4個屬性(A,B,C和Foo)在我的代碼

Class Test { 
    public $a = 'a'; 
    protected $b = 'b'; 
    private $c = 'c'; 
} 

$test = new Test(); 
$test->foo = "bar"; 

會發生什麼一小爲例。
屬性被視爲公共財產,因爲我可以做

echo $test->foo; // Gives : bar 

相反bÇ被視爲私人財產

echo $test->b; // Gives : Cannot access protected property Test::$b 
echo $test->c; // Gives : Cannot access private property Test::$c 

 


我嘗試了兩種解決方案,讓我$測試對象的所有屬性(A,B,C和Foo)

第一

var_dump(get_object_vars($test)); 

其中給出

array (size=2) 
    'a' => string 'a' (length=1) 
    'foo' => string 'bar' (length=3) 

 
而第二種解決方案

$reflection = new ReflectionClass($test); 
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED); 
foreach($properties as $property) { 
    echo $property->__toString()."<br>"; 
} 

其中給出

Property [ public $a ] 
Property [ protected $b ] 
Property [ private $c ] 

 
在第一種情況下,私有財產丟失,並在「實例化之後的」第二種情況的屬性丟失。

不知道我能做些什麼來獲得所有屬性?
(最好是與反思,因爲我也想知道,如果一個屬性是公共的,私人...)

回答

2

使用ReflectionObject而不是ReflectionClass如果你還需要列出動態創建的對象的屬性:

$test = new Test(); 
$test->foo = "bar"; 

$class = new ReflectionObject($test); 
foreach($class->getProperties() as $p) { 
    $p->setAccessible(true); 
    echo $p->getName() . ' => ' . $p->getValue($test) . PHP_EOL; 
} 

請注意,我已使用ReflectionProperty::setAccessible(true)以訪問protectedprivate屬性的值。

輸出:

a => a 
b => b 
c => c 
foo => bar 

Demo

+0

的OP也希望其被所述對象實例化之後設置的屬性。 –

+0

@Amal檢查我的更新 – hek2mgl

+0

這就是我一直在尋找的。謝謝! – Typhon