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,
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
Written on April 11, 2018 by Manuel Wutte. The term “reflection” in software development means that a program knows its own structure at runtime and can also modify it. This capability is also referred to as “introspection”.
How about
ReflectionProperty::getValue
- Gets the properties value. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With