Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 608
André Avatar asked Feb 14 '11 17:02

André


People also ask

How do you access the properties of an object in PHP?

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 .

What is reflection method in PHP?

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”.


1 Answers

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.

like image 163
Gordon Avatar answered Oct 15 '22 21:10

Gordon