gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:12:43 24 4
gpt4 key购买 nike

我在 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 循环中获取属性值?

最好的问候,

最佳答案

怎么样

在你的情况下:

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

旁注,因为您的对象只有公共(public)成员,所以您也可以 iterate it directly

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

或使用 get_object_vars 获取它们成一个数组。

关于PHP 反射类。如何获取属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4995321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com