PHP使用foreach为对象更改默认迭代器

With an object like this:

class test {
var $propa = 'a';
var $propb = 'b';
var $propc = 'c';
var $propd = array(1,2,3,4);
}

How do I iterate with test::$propd using foreach WITHOUT direct reference? eq:

$t = new test;
foreach ($t as $k => $v){
echo 'propd['.$k.']='.$v.', ';
}
// propd[0]=1, propd[1]=2, propd[2]=3, ...

Is there some stuff involving implement ArrayAccess? Thx!

I would recommend separating functionality, and setting your properties as private.

Example:

class Test {

   private $propertyA = 'a';
   private $propertyB = 'b';

   public function getProperties()
   {
        return [
           'propertyA' => $this->propertyA,
           'propertyB' => $this->propertyB
        ];
   }

}

However, if the property values are to change then do getters and setters for the properties.

With the above code you can do:

<?php

$test = new Test;
foreach ($test->getProperties() as $key => $value) {
    echo $key . ' = ' . $value;
}

?>

You can also limit what properties you want to output with this method.