2014-04-10 309 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