2011-02-14 85 views
6

我在PHP中使用反射類,但我沒有關於如何獲得反射實例中的屬性值的線索。有可能的?PHP反射類。如何獲取屬性的值?

代碼:

<?php 

class teste { 

    public $name; 
    public $age; 

} 

$t = new teste(); 
$t->name = 'John'; 
$t->age = '23'; 

$api = new ReflectionClass($t); 

foreach($api->getProperties() as $propertie) 
{ 
    print $propertie->getName() . "\n"; 
} 

?> 

我怎樣才能獲得的foreach循環內的propertie值?

最好的問候,

回答

11

如何

你的情況:

foreach ($api->getProperties() as $propertie) 
{ 
    print $propertie->getName() . "\n"; 
    print $propertie->getValue($t); 
} 

在阿里納斯,因爲你的對象只有公共成員,你也可以同樣iterate it directly

foreach ($t as $propertie => $value) 
{ 
    print $propertie . "\n"; 
    print $value; 
} 

get_object_vars接他們到一個數組。

+1

非常感謝,它的工作!最好的祝福, – 2011-02-14 17:51:07

0

另一種方法是使用getDefaultProperties()方法,如果你不想實例化那個類,例如。

$api->getDefaultProperties(); 

這是你的完整的例子減少你在找什麼...

class teste { 

    public $name; 
    public $age; 

} 

$api = new ReflectionClass('teste'); 
var_dump($api->getDefaultProperties()); 

注意:您也可以使用ReflectionClass的命名空間內。例如,

$class = new ReflectionClass('Some\Namespaced\Class'); 
var_dump($class->getDefaultProperties()); 
相關問題