object to array
Posted: Fri Aug 18, 2006 6:39 pm
is there a function that takes an object and returns it's member variables in an array?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
[feyd@home]>php -r "class foo{public $someVar; private $someOtherVar; public function __construct(){$this->someVar = mt_rand(1,100); $this->someOtherVar = mt_rand(100,200);}} $foo = new foo(); var_dump($foo, (array)$foo);"
object(foo)#1 (2) {
["someVar"]=>
int(20)
["someOtherVar:private"]=>
int(135)
}
array(2) {
["someVar"]=>
int(20)
[" foo someOtherVar"]=>
int(135)
}Code: Select all
$array = get_object_vars($obj);Code: Select all
public function loadFromArray($array){
$object_vars = get_object_vars($this);
$values = array_intersect_key($array, $object_vars);
foreach($values as $key => $val){
$this->{$key} = $val;
}
}