Get public properties that aren’t static with PHP Reflection

Dlk :

I need to use PHP Reflection API to get all the publicly accessible properties for a class that aren’t static.

In order to get just the public properties that are not static, the only way I could see to do it was to get the IS_STATIC properties and use array_diff() to get only the public ones.

Final class looks like this :

class foo {
    public static $a;
    public static $b;
    public static $c;

    public $d;
    public $e;
    public $f;

    public function reflect()
    {
        $reflection = new ReflectionClass($this);
        $public = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
        $static = $reflection->getProperties(ReflectionProperty::IS_STATIC);
        $properties = array_diff($public, $static);
        foreach($properties as $property) {
            echo $property->name . "n";
        }
    }

}

Call:

$foo = new foo;
$foo->reflect();

The output from reflect() now looks like this :

d
e
f

Question : Is there a better way to do this ?

Note : My original class is too long! This class is an example similer to mine.

u_mulder :

The fastest way is definitely use get_object_vars, for your case:

print_r(get_object_vars($foo)); 
// outputs
Array
(
    [d] => 
    [e] => 
    [f] => 
)

Keys are propertes' names.

But instantiating an instance can be quite heavy. So, you still can use reflection and a little of filtering:

public function reflect()
{
    $reflection = new ReflectionClass($this);
    $properties =  array_filter(
        $reflection->getProperties(ReflectionProperty::IS_PUBLIC),
        function ($property) {
            return !$property->isStatic();
        }
    );
    foreach($properties as $property) {
        echo $property->name . "\n";
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9706&siteId=1