我在 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 循环内的属性值?
此致,
怎么样
-
ReflectionProperty::getValue- 获取属性值。
在你的情况下:
foreach ($api->getProperties() as $propertie)
{
print $propertie->getName() . "\n";
print $propertie->getValue($t);
}
顺便说一句,由于您的对象只有公共成员,因此您也可以直接迭代它
foreach ($t as $propertie => $value)
{
print $propertie . "\n";
print $value;
}
或使用以下命令获取它们get_object_vars到一个数组中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)