Object to Array, Object to stdClass in PHP

objectconverter

ObjectConverter - one of those classes you won't see the point of until you hit the problem.

Problem: When you convert an object (instance of a class) to an array in PHP, only the public properties are included; often you need public, protected, private and inherited properties to be visible, indeed there isn't any real way to expose all properties of an object without adding a "toArray" method to class itself; simply there is no simple way to do this (private properties are private for a reason!).

Solution: ObjectConverter :) This is a utility class which will turn any given instance in to either an array or a bare stdClass instance; effectively exposing all properties so you can persist or transfer your objects easily.

Note: afaik no other "object to array" script can do this, and after playing with multiple approaches over the years I finally settled on this implementation which does *not* use reflection or any such heavy weight trickery.

Usage:
$array = ObjectConverter::toArray( $obj );
$stdClass = ObjectConverter::toStdClass( $obj );

Download: ObjectConverter PHP Script (php5 only)

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Printed from: http://webr3.org/blog/php/object-to-array-object-to-stdclass-in-php/ .
© Your Name Here 2012.

6 Comments   »

  • adel says:

    That's awsomme !!!!!!!!!!!!!!

    thanks a lot

  • Mike D says:

    This is great. I was looking for this to convert a complex object onto an array to feed into a Zend Framework Form.
    Thanks!!!!!

RSS feed for comments on this post , TrackBack URI

Leave a Reply

Additional comments powered by BackType

  • webr3 avatar