Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the property's scope within class

Tags:

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();
like image 823
Mark Tomlin Avatar asked Oct 02 '10 20:10

Mark Tomlin


1 Answers

Using ReflectionProperty, it's possible. You could create a helper function if you want to make it less verbose:

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

?>
like image 167
Matthew Avatar answered Sep 26 '22 12:09

Matthew