I'm looking for an efficient way to use json_encode for an array of objects. The issue I have is that my objects all have private properties (use getters and setters) and json_encode won't pull those in. So I created a jsonSerialize function for an object with returns the private variables but I don't know how to execute the function for each object in the array efficiently. I could use a loop to execute the jsonSerialize function for each object but that I'm afraid that may be too slow.
class car
{
private $make, $model;
public function jsonSerialize()
{
return get_object_vars($this);
}
}
Controller function to return list of cars in json format
$cars = $db->getAllCars(); //returns an array of objects using fetchall
return json_encode($cars);