如何 return PHP 中对象的 属性 的访问修饰符级别?

How to return the access-modifier level of an Object's property in PHP?

说我有这个 class :

class Foo {
  var $pu = 0;
  private $pr = 1;
}

我需要找到一种方法来检查一个 属性 的访问修饰符级别,例如:

class Foo {
  var $pu = 0;
  private $pr = 1;

  function return_all_public () {
    $publics = [];
    for (get_object_vars($this) as $key => $value) {
      // if $this->{$key} is public then array_push($publics, $key);
    }
    return $publics;
  }
}

这只是一个例子,功能不是我要实现的,只是想知道如何查看一个属性(public,protected的访问修饰符的级别还是私人的?)

使用ReflectionObject:

foreach ((new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
    $publics[] = $property->getName();
}

甚至:

$publics = array_map(function (ReflectionProperty $property) {
    return $property->getName();
}, (new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC));

参考文献:
http://php.net/manual/en/class.reflectionobject.php
http://php.net/manual/en/reflectionclass.getproperties.php http://php.net/manual/en/class.reflectionproperty.php

编辑澄清 - 不要使用它,这显然是一个错误,似乎已在 php 版本 7 中修复。 http://codepad.viper-7.com/lyULdW(将版本更改为 <=5.6 以查看它是否正常工作)

@deceze 的回答是最可靠的,但是正如您指出的,在不实例化新对象的情况下调用函数的偏好:

class Foo 
{
    var $pu = 0;
    private $pr = 1;

    function return_all_public () {
        return call_user_func('get_object_vars', $this);
    }
}

尚不清楚此范围问题是功能还是错误!