Reflection Properties Filter

I have a class with public, public static, private and private static properties, and I'm trying to get only public. For some reason, I just can't get the filter, I tried

ReflectionProperty::IS_PUBLIC & ~ReflectionProperty::IS_STATIC

or

ReflectionProperty::IS_PUBLIC & (ReflectionProperty::IS_PUBLIC | ~ReflectionProperty::IS_STATIC)

among other things, but I also get static public or private static.

+5
source share
2 answers

You will need to query all the publics and then filter out the public statistics as follows:

$ro = new ReflectionObject($obj);

$publics = array_filter(
    $ro->getProperties(ReflectionProperty::IS_PUBLIC), 
    function(ReflectionProperty $prop) {
        return !$prop->isStatic();
    }
);
+3
source

get all the publics and all the statics, and then cross them:

class Test{
 public static $test1 = 'test1';
 private static $test2 = 'test2';
 public $test3 = 'test3';
}
$test = new Test();
$ro = new ReflectionObject($test);
$publics = $ro->getProperties(ReflectionProperty::IS_PUBLIC);
$statics = $ro->getProperties(ReflectionProperty::IS_STATIC);
var_export(array_diff($publics, $statics));

returns:

array ( 1 => ReflectionProperty::__set_state(array( 'name' => 'test3', 'class' => 'Test', )), )
+1
source

All Articles