object to array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

object to array

Post by Luke »

is there a function that takes an object and returns it's member variables in an array?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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)
}
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

All I can think of is serializing.. and then writing your own unserialize function.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

$array = get_object_vars($obj);
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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