How do I tell if a variable is public or private from within a PHP class?

php

Solution

Use Reflection. I've modified an example from the PHP manual to get what you want:

class Person
{
  public $name = 'Fred';
  public $email = 'fred@example.com';
  private $password = 'sexylady';

  public function __construct()
  {
    $reflect = new ReflectionObject($this);
    foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) 
    {
      $propName = $prop->getName();
      echo $this->$propName . "\n";
    }
  }
}

Problem

I'm sure I could find this on PHP.net if only I knew what to search for! Basically I'm trying to loop through all public variables from within a class. To simplify things: ``` <?PHP class Person { public $name = 'Fred'; public $email = 'fred@example.com'; private $password = 'sexylady'; public function __construct() { foreach ($this as $key=>$val) { echo "$key is $val \n"; } } } $fred = new Person; ``` Should just display Fred's name and email....

Original source

Related problems