Get public properties that aren't static with PHP Reflection

Posted in PHP -

PHP has a Reflection API adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. I needed to use it to get all the publicly accessible properties for a class that aren't static, but there doesn't seem to be a way to get this "out of the box".

This post has my solution, but feel free to let me know a better way of doing it in the comments.

tl;dr

$reflection = new ReflectionClass($this);
$public = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$static = $reflection->getProperties(ReflectionProperty::IS_STATIC);
$properties = array_diff($public, $static);

$properties will now contain only the properties that are public and not static. If you are using namespaces, you'll probably need to prefix ReflectionClass and ReflectionProperty with \ so they look like \ReflectionClass and \ReflectionProperty.

Longer answer

The following class "foo" has three public static properties (a, b, c) and three regular public properties (d, e, f). The "reflect" method echoes out all the public properties.

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

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

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

}

Calling the "reflect" method liek this:

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

will output this:

a
b
c
d
e
f

This includes the static properties, and I couldn't work out any way to exclude them. Again, as noted at the top of this post, please feel free to let me know if there is a way to do it easily when calling the getProperties() method.

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.

The revised 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";
        }
    }

}

The output from reflect() now looks like this:

d
e
f

Is there a better way to do this? Please let me know in the comments section.



Related posts:


Comments