Explanation of your foreach loop:
- Each loop you get key name of array and value of array element
- Than you set $obj property here $obj->$name = $value;
- $name is replaced with array key name therefore it looks like $obj->a = $value;
To pass array to object, use magic setter method:
class A {
public $a;
public $b;
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
$obj = new A();
$arr = array ("a" => 1, "b" => 2);
foreach ($arr as $name => $value) {
$obj->__set($name, $value);
}
All of the object are as array automatically, so to fetch it back as array, you can loop object directly:
foreach ($obj as $key => $value) {
print "$key => $value\n";
}
To get directly full array from object you can make another method which will do this for you:
public function getAsArray() {
$arr = array();
foreach ($this as $key => $value) {
$arr[$key] = $value;
}
return $arr;
}