I have a little project going and since I am not the best at OOP I have come here for some help. I have a class called "truckinfo"
class truckinfo
{
public $vendor;
public $truckcount;
public $plate;
}
now I get the information like plate or vendor from somewhere else, and then display the truck in a list. I plan on creating the list somewhat like this
for($i = 0; $i < 3; $i++){
$truck = new truckinfo();
$truck->plate = "abc" . $i;
$truck->truckcount = $i + 5;
echo $truck->truckcount;
}
My question is, is it possible after displaying all the trucks to get the information from the first truck (in this case truck with plate "abc0") or can I only get the info for the latest one that got into the loop?
Thank you in advance.
With this small piece of logic you have no variable that holds the reference to the first truck object, so there is (maybe by some trickery I'm unaware of) no way of obtaining that object. Often in basic courses you get introduced to so called 'management' classes that construct objects of a kind and keep track of them in an array (or other data structure), allowing you to search for them etc. Especially if you start working towards a small basic CRUD application it is nice to have that responsibility grouped in a separate class. This way you can manage identifications of objects as well as more cleanly get and return the wanted object that uniquely identifies it.
Let me add that I assume for your example storing them in the associative array as: $trucks[$truck->plate] = $truck
creating yourself a small mapping of license plates to truck info objects would suffice. You can then directly access and retrieve them by the license plate.
$trucks = [];
for($i = 0; $i < 3; $i++){
$truck = new truckinfo();
$truck->plate = "abc" . $i;
$truck->truckcount = $i + 5;
echo $truck->truckcount;
$trucks[$truck->plate] = $truck
}
echo $trucks['abc0']->truckcount;