tags:

views:

36

answers:

2

Hi, 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 = '[email protected]';
  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....

A: 

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 = '[email protected]';
    private $password = 'sexylady';

    public function __construct()
    {
        $params = get_class_vars(__CLASS__);
        foreach ($params AS $key=>$val)
        {
            echo "$key is $val \n";
        }
    }
}
?>
TiuTalk
Thanks for the link, however that usage still reveals private vars...
MQA
+3  A: 

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

class Person
{
  public $name = 'Fred';
  public $email = '[email protected]';
  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
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
Why googling, when the answer is already on SO: http://stackoverflow.com/questions/294582/php-5-reflection-api-performance
Boldewyn
Ah thanks, not heard of it either - although, like Boldewyn, I'm a little worried about the performance issues!
MQA
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