反射属性过滤器

时间:2013-04-03 09:46:06

标签: php

我有一个包含公共,公共静态,私有和私有静态属性的类,我试图只获取公共属性。我出于某种原因无法获得过滤器,我试过

ReflectionProperty::IS_PUBLIC & ~ReflectionProperty::IS_STATIC

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

除了其他方面,我要么继续获取静态公共或私有静态。

2 个答案:

答案 0 :(得分:3)

您需要查询所有公开内容,然后像这样过滤掉公共静态信息:

$ro = new ReflectionObject($obj);

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

答案 1 :(得分:1)

获取所有公众和所有静态然后与它相交:

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));

返回:

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