简体   繁体   中英

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,

How about

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.

Another method is to use the getDefaultProperties() method, if you don't want to instantiate that class, eg.

$api->getDefaultProperties();

Here's your full example reduced to what you're looking for...

class teste {

    public $name;
    public $age;

}

$api = new ReflectionClass('teste');
var_dump($api->getDefaultProperties());

Note: you can also use namespaces inside of that ReflectionClass. eg,

$class = new ReflectionClass('Some\Namespaced\Class');
var_dump($class->getDefaultProperties());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM