casting arrays as objects

From: Date: Fri, 13 Apr 2001 20:12:11 +0000
Subject: casting arrays as objects
Groups: php.general 
Request: Send a blank email to php-general+get-48480@lists.php.net to get a copy of this message
Can you cast an array to an object of your choosing? If so, will the keys of the array match up with the attributes of your object? Say I have a class like this: class Foo { var $foo; var $bar; function Foo($foo = '', $bar = '') { ... } ... } Then I have an array like: $array['foo'] = "Hello"; $array['bar'] = "world"; If I do this: $foo = new Foo(); $foo = (object)$array; I've seen something similar done, but how do you keep $foo from forgetting which class it belongs to? The second assignment is independent of the first one, so $foo should become a plain object and forget that it's a "Foo" object. Any ideas? By the way, I was thinking this would be a really nifty way to fetch rows from the database into a pre-written class instead of doing it all manually. You'd have all the object properties automatically set by: $my_object = (object)$db->fetchRow(DB_FETCHMODE_ASSOC); I'm just worried about the object losing its membership in its original class. Dean.

« previous php.general (#48480) next »