Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_encode class private members

Tags:

json

php

I'm trying to JSON encode some objects in PHP, but I'm facing a problem: I want to encode data which is kept by a class private members. I found this piece of code to encode this object by calling an encode function like:

public function encodeJSON()  {      foreach ($this as $key => $value)      {          $json->$key = $value;      }      return json_encode($json);  } 

However, this only works if the object I want to encode does not contain other objects inside, which is the case. How can I do to encode not only the "outer" object, but encode as well any members that are objects too?

like image 575
rrrcass Avatar asked Aug 10 '11 04:08

rrrcass


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is the difference between json_encode and Json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

Can you JSON encode an object in PHP?

To encode objects into a JSON formatted string in PHP, you can use the json_encode(value, options, depth) function. The first parameter specifies the PHP object to encode. You can control how the PHP object will be encoded into JSON by passing a combination of bitmasks in the second parameter.


2 Answers

The best method to serialize an object with private properties is to implement the \JsonSerializable interface and then implement your own JsonSerialize method to return the data you require to be serialized.

<?php  class Item implements \JsonSerializable {     private $var;     private $var1;     private $var2;      public function __construct()     {         // ...     }      public function jsonSerialize()     {         $vars = get_object_vars($this);          return $vars;     } } 

json_encode will now serialize your object correctly.

like image 141
samsamm777 Avatar answered Sep 20 '22 00:09

samsamm777


If you're using php 5.4 you can use the JsonSerializable interface: http://www.php.net/manual/en/class.jsonserializable.php

You just implement a jsonSerialize method in your class which returns whatever you want to be encoded.

Then when you pass your object into json_encode, it'll encode the result of jsonSerialize.

like image 30
lucas Avatar answered Sep 23 '22 00:09

lucas