Page 1 of 1

object to array

Posted: Fri Aug 18, 2006 6:39 pm
by Luke
is there a function that takes an object and returns it's member variables in an array?

Posted: Fri Aug 18, 2006 6:52 pm
by feyd
The property names? or the property values?

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)
}

Posted: Fri Aug 18, 2006 6:54 pm
by s.dot
All I can think of is serializing.. and then writing your own unserialize function.

Posted: Fri Aug 18, 2006 6:55 pm
by Jenk

Code: Select all

$array = get_object_vars($obj);

Posted: Fri Aug 18, 2006 7:00 pm
by Luke
I ended up using object_get_vars....

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