如何从该类内部或外部对一个类的所有字段执行 foreach?例如,给定以下类:
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;
}
}
foreach()
方法中的in如何showAll()
引用$a
、$b
、$c
和$d
属性?
就此而言,可以从类外获取所有公共属性吗?
$params = array();
$foo = new Foo($params);
foreach ($foo->allProperties as $f=>$v) { // how to do this?
echo "{$f}: {$v}\n";
}