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 循环内的属性值?
此致,
I'm using the reflection class in PHP, but I'm with no clues on how to get the values of the properties in the reflection instance. It is possible?
The code:
<?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";
}
?>
How can I get the propertie values inside the foreach loop?
Best Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样
ReflectionProperty::getValue
-获取属性值。在你的情况下:
顺便说一句,由于你的对象只有公共成员,你也可以 直接迭代
或使用
get_object_vars
放入数组中。How about
ReflectionProperty::getValue
- Gets the properties value.In your case:
On a sidenote, since your object has only public members, you could just as well iterate it directly
or fetch them with
get_object_vars
into an array.另一种方法是使用 getDefaultProperties() 方法(如果您不想)实例化该类,例如
这是您要查找的完整示例...
注意:您还可以在该 ReflectionClass 内使用名称空间。例如,
Another method is to use the getDefaultProperties() method, if you don't want to instantiate that class, eg.
Here's your full example reduced to what you're looking for...
Note: you can also use namespaces inside of that ReflectionClass. eg,