5

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....

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
watermanio
  • 235
  • 1
  • 11

2 Answers2

7

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";
    }
  }
}
Rowlf
  • 1,752
  • 1
  • 13
  • 15
  • Cool, I haven't heared of this before. +1. However, have you any knowledge of the performance of this class compared to something like get_class_vars? – Boldewyn Feb 05 '10 at 11:31
  • Why googling, when the answer is already on SO: http://stackoverflow.com/questions/294582/php-5-reflection-api-performance – Boldewyn Feb 05 '10 at 11:32
  • Ah thanks, not heard of it either - although, like Boldewyn, I'm a little worried about the performance issues! – watermanio Feb 05 '10 at 11:34
  • Reflection is a little slower but if it's got the functionality you need you should go for it regardless. It's not going to be much of an overhead, and it's a very powerful instrument. – Rowlf Feb 05 '10 at 11:37
0

http://php.net/manual/en/function.get-class-vars.php

You can use get_class_vars() function:

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

    public function __construct()
    {
        $params = get_class_vars(__CLASS__);
        foreach ($params AS $key=>$val)
        {
            echo "$key is $val \n";
        }
    }
}
?>
Thiago Belem
  • 7,732
  • 5
  • 43
  • 64