foreach on all object properties

loops, php

Solution

Use Reflection class: Class Reflectionclass Manual ( PHP 5 )

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

?>

Problem

How does one perform a foreach over all the fields of a class, either from within that class or from without? For instance, given the following class: ``` class Foo { public $a; public $b; private $c; private $d; public function __construct($params) { foreach($params as $k=>$v){ $this->$k = $v; } } public function showAll() { $output = array(); foreach (this as $k=>$v) { // How to refer to all the class properties? $output[$k] = $v; } return $output; } } ``` How might the `foreach()` in the `showAll()` method refer to the `$a`, `$b`, `$c`, and `$d` properties? For that matter, can one get all the public properties from outside the class? ``` $params = array(); $foo = new Foo($params); foreach ($foo->allProperties as $f=>$v) { // how to do this? echo "{$f}: {$v}\n"; } ```

Original source

Related problems