maxhb
maxhb

Reputation: 8865

Get scope of class vars

I'm trying to fetch a list of properties (class vars) defined by a class. This can be done using get_class_vars(). Unfortunately I need to know the scope (public/private/protected) of those vars, too.

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

Output:

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

Is there any way to get the scope, so that I would get the information that e.g. property $protectedProperty is a protected var?

Background: Still trying to find a work around to solve the nasty php bug already described in my question Changed behavior of (un)serialize()?

Upvotes: 2

Views: 90

Answers (2)

maxhb
maxhb

Reputation: 8865

Just in case some one needs a solution to the described problem.

Based on the answer of @Kelvin I came up with the following implementation.

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

Output:

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

Upvotes: 0

Kelvin
Kelvin

Reputation: 690

You should using 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);

?>

Upvotes: 2

Related Questions