PHP反射类.如何获取属性的值?

And*_*dré 6 php reflection get

我在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";
}

?>
Run Code Online (Sandbox Code Playgroud)

如何在foreach循环中获取属性值?

最好的祝福,

Gor*_*don 11

怎么样

在你的情况下:

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

在旁注中,由于您的对象只有公共成员,因此您也可以直接迭代它

foreach ($t as $propertie => $value)
{
    print $propertie . "\n";
    print $value;
}
Run Code Online (Sandbox Code Playgroud)

或者将它们get_object_vars带入数组中.