Jump to content

[SOLVED] Creating an array of custom objects


Tuskony

Recommended Posts

Hey guys,

 

How do you create an array of custom objects? I have a Truck class and I want to find all the trucks the user has stored on the server and load them into truck class objects and bind those objects in an array so I can Access them like this:

 

$Trucks = new array of Truck();

$Trucks[0]->SetName['Some name'];
$Trucks[0]->SetDesc['Desc'];

 

or something similar to that.

Hey guys,

 

How do you create an array of custom objects? I have a Truck class and I want to find all the trucks the user has stored on the server and load them into truck class objects and bind those objects in an array so I can Access them like this:

 

$Trucks = new array of Truck();

$Trucks[0]->SetName['Some name'];
$Trucks[0]->SetDesc['Desc'];

 

or something similar to that.

 

First, make an array:

 

$trucks = array()

 

Then fill it up:

 

$trucks[] = new Truck();

 

That automatically places a new Truck object at the end of the array.  Now, you can access it like normal:

 

$trucks[0]->setName('name');
$trucks[0]->setDesc('desc');

 

Keep in mind, you can do this in a loop if you have a lot of objects you want to add to the array:

 

$trucks = array();

for($i = 0; $i < 100; $i++)
{
   $trucks[$i] = new Truck();
   $trucks[$i]->setName('Truck_' . $i);
   $trucks[$i]->setDesc('Desc_' . $i);
}

Ah! Thank you very much! I was confused as to the beginning syntax!

 

$trucks = array();
$trucks[] = new Truck;

 

You're a life saver! Thanks! I'm a C++ programmer at heart so it takes a little getting used to get a knac for all the little things like that!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.