在课堂上找到属性的范围

时间:2010-10-02 20:10:01

标签: php reflection

class ParentClass
{
    public function list()
    {
        foreach ($this as $property => $value)
        {
            if (is_public($this->$property))
                echo 'public: ';
            else if (is_protected($this->$property))
                echo 'protected: ';
            echo "$property => $value" . PHP_EOL;
        }
    }
}

class ChildClass extends ParentClass
{
    protected $Size = 4;
    protected $Type = 4;
    public $SubT = 1;
    public $UVal = NULL;
}

$CC = new ChildClass;
$CC->list();

1 个答案:

答案 0 :(得分:7)

使用ReflectionProperty,这是可能的。如果你想让它更简洁,你可以创建一个辅助函数:

<?php
function P($obj, $name)
{
  return new ReflectionProperty($obj, $name);
}

class Foo
{
  public $a;

  public function __construct()
  {
    foreach (array_keys(get_object_vars($this)) as $name)
    {
      if (P($this, $name)->isPublic())
      {
        echo "Public\n";
      }
    }
  }
}

new Foo();

?>