Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode an array of objects with private properties

Tags:

php

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);
like image 238
Ralph Avatar asked Dec 28 '25 16:12

Ralph


2 Answers

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);
     }
} 
like image 166
Mathew B. Avatar answered Dec 30 '25 08:12

Mathew B.


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);
like image 29
clean_coding Avatar answered Dec 30 '25 08:12

clean_coding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!