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";
}