PHP Reflection Class. How to get the values of the properties?

拟墨画扇 提交于 2019-12-01 04:35:06

How about

In your case:

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

On a sidenote, since your object has only public members, you could just as well iterate it directly

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

or fetch them with get_object_vars into an array.

Another method is to use the getDefaultProperties() method, if you don't want to instantiate that class, eg.

$api->getDefaultProperties();

Here's your full example reduced to what you're looking for...

class teste {

    public $name;
    public $age;

}

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

Note: you can also use namespaces inside of that ReflectionClass. eg,

$class = new ReflectionClass('Some\Namespaced\Class');
var_dump($class->getDefaultProperties());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!