casting arrays to objects

[email protected] ("Dean Hall")
Newsgroups php.lang
Message-ID <[email protected]>
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.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.