How can I convert an object to an array, and should I?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
zeek
Forum Commoner
Posts: 48
Joined: Mon Feb 27, 2006 7:41 pm

How can I convert an object to an array, and should I?

Post by zeek »

I am new to object oriented coding. I have written my code so that each user is an object. When the user object is created, it sets all of the user objects attributes, some of which take multiple steps and database queries to determine.

I need (I want) to make an array of user objects, so that I can list them, compare them, etc. I am assuming that having many objects in an array will take up more cpu resources that to have many sub-arrays. Since I'll not be modifying the data, or calling any methods, I'm assuming I should convert the objects to arrays. But I can't find instructions (a function) to do this.

My questions are...

1. Does an object take up more cpu resources than an array with the same attributes/elements?

2. If so, how do you convert an object to an array?

If I am over-complicating this, please tell me. Thanks in advance.
Jixxor
Forum Commoner
Posts: 46
Joined: Wed Jun 07, 2006 5:53 pm
Location: Lakeland, FL

Post by Jixxor »

You might want to check out this tutorial for some understanding.

Maugrims PHPDataObjects Tutorial

I've probably re-read this tutorial about 5 or 6 times now, and it never gets old. Great stuff on learning about classes and data objects. And it falls in the lines of what you ultimately would like to do.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Does an object take up more cpu resources than an array with the same attributes/elements?
I don't think so... as to converting object to array, take a look at get_object_vars()
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

It does not take up much more CPU resources - it does consume more memory (another performance measure) but it's not prohibatively expensive. get_object_vars() is very useful for extracting an object's variables which is probably the fastest route to what you want - implement inside a getArray() method for your class and work from there.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

I think the big question here is: do you have a performance or memory problem currently? If you don't then create the cleanest, best design you can and worry about those things if/when the become a problem.
(#10850)
Post Reply