【问题标题】:Get scope of class vars获取类变量的范围
【发布时间】:2016-06-07 22:28:10
【问题描述】:

我正在尝试获取由类定义的属性列表(类变量)。这可以使用get_class_vars() 来完成。不幸的是,我也需要知道这些变量的范围(公共/私有/受保护)。

<?php
class test {
  public $publicProperty = 1;
  protected $protectedProperty = 2;
  private $privateProperty = 3;

  public function getClassVars() {
    return get_class_vars(__CLASS__);
  }

}

$test = new test();
var_dump($test->getClassVars());

输出:

array(3) {
  ["publicProperty"]=> int(1)
  ["protectedProperty"]=> int(2)
  ["privateProperty"]=> int(3)
}

有什么方法可以获取范围,这样我就可以获取信息,例如属性$protectedProperty 是受保护的变量?

背景:仍在尝试解决我的问题Changed behavior of (un)serialize()?中已经描述的讨厌的php错误

【问题讨论】:

  • print_r()给出类似于var_dump()的输出,没有附加范围信息。

标签: php class oop properties


【解决方案1】:

以防万一有人需要解决所描述的问题。

根据@Kelvin 的回答,我想出了以下实现。

<?php
class TestClass {
    public    $publicProperty  = 1;
    protected $protectedProperty  = 2;
    private   $privateProperty  = 3;

    /**
    * Returns an associative array of structure scope => property names
    * @return array
    **/
    public function getPropertiesByScope() {
      $properties = [];
      $scopes = [
        ReflectionProperty::IS_PUBLIC => 'public',
        ReflectionProperty::IS_PROTECTED => 'protected',
        ReflectionProperty::IS_PRIVATE => 'private'
      ];

      foreach($scopes as $scope => $name) {
        $properties[$name] = [];

        $reflect = new ReflectionClass($this);
        $props  = $reflect->getProperties($scope);
        foreach($props as $p) {
          $properties[$name][] = $p->name;
        }
      }

      return $properties;
    }
}

$test = new TestClass();
var_dump($test->getPropertiesByScope());        
?>

输出:

array(3) {
  ["public"]=>
  array(1) {
    [0]=>
    string(14) "publicProperty"
  }
  ["protected"]=>
  array(1) {
    [0]=>
    string(17) "protectedProperty"
  }
  ["private"]=>
  array(1) {
    [0]=>
    string(15) "privateProperty"
  }
}

【讨论】:

  • 或者另一种方式是使用php kint库来调试一切
  • 非常好的库,但无助于在运行时检查类属性。
【解决方案2】:

你应该使用ReflectionClass

<?php
class Foo {
    public    $foo  = 1;
    protected $bar  = 2;
    private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 2014-04-18
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多