Rather then make continued calls to my database I'd like to load the contents of several tables into classes, do the manipulation of data within the class and at the end of the program update the database from the values in the class instances. The question I have is does anyone have or could you point me to examples of code on how to load multiple class instances into an array. For instance, I do a query and get the recordset from the database. Now I've defined my class and the constructor's parameters are the same as the fields found in the record. I can see how to do this for a single instance of the class, or for multiple instances of the class using different a name for each instance. What I can't figure out is the syntax to load the new class instance into an array, giving me an array of class instances. Speaking of the array, to load the class instance into the array does the array have to be a regular array, which I'd have to iterate through to find the correct instance/db record, or is there any way to build an associative array of the class instances using the ID of the record as the index, which would make it faster to retrieve the data?
In short does anyone have code examples of how to build an array of class instances and retrieve the values from that array?
Thanks,
Tom
load an array of class instances
Moderator: General Moderators
-
SidewinderX
- Forum Contributor
- Posts: 407
- Joined: Fri Jul 16, 2004 9:04 pm
- Location: NY
Re: load an array of class instances
You can serialize the objects.
Re: load an array of class instances
thanks for the reply. I looked at the serialize, but I'm not convinced that's the way to go since I have to do a number of data manipulations before updating the database record. This type of process would be easy since the class instance will, in fact, have the same data definition as the database record. Again, the question is how to load a class instance into an array, then be able to retrieve a class from the array and change a data element. I've done a google search, but nothing so far.
Regards,
Tom
Regards,
Tom
Re: load an array of class instances
If the objects has the exact same properties as the database columns, use get_object_vars() will give you the object contents in an associative array.
But I recommend using a foreach loop like this, as it is less error prone (eg. if you add another property dynamically):
And to load the data into objects, well, you can either do it with a foreach loop in a constructor of the object or do it with an external foreach loop.
But I recommend using a foreach loop like this, as it is less error prone (eg. if you add another property dynamically):
Code: Select all
$array = array();
foreach($object_array as $obj)
{
$array[] = array('title' => $obj->title/*, ...*/);
}