3

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);
1

2 Answers 2

9

You can't use json_encode for objects, it's written in the manual (http://php.net/manual/en/function.json-encode.php)

First you need to implement in your object the JsonSerializable interface to achieve what you're looking for (http://php.net/manual/en/jsonserializable.jsonserialize.php).

In your case you're missing the interface declaration. Try this

class car  implements JsonSerializable
{
     private $make, $model;
     public function jsonSerialize()
     {
          return get_object_vars($this);
     }
} 
Sign up to request clarification or add additional context in comments.

Comments

3

You can use the JsonSerializable type like this:

class Car implements JsonSerializable
{
     private $make, $model;

     public function jsonSerialize() {
         return array($this->make, $this->model);
     }
} 

var $car = new Car();
echo json_encode($car, JSON_PRETTY_PRINT);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.