title: Extending json_encode for nested objects
body: <p>I am using <strong>PHP 5.2.x</strong> and want to encode objects of my custom PHP classes with only private members. One of the private members is an array of objects of another custom class.</p>
  
  <p>I tried the solution outlined in <a href="https://stackoverflow.com/a/7005915/17716">https://stackoverflow.com/a/7005915/17716</a>, but that obviously does not work recursively. The only solution that I can see is extending the json_encode method somehow ,so that the class' version of the json_encode method is called instead of the default method.</p>
  
  <p>For reference, the code is as follows:</p>
  
  <pre><code>Class A {
      private $x;
      private $y;
      private $z;
      private $xy;
      private $yz;
      private $zx;
  
      public function f1() {
          ...
      }
  
      public function f2() {
          ...
      }
      .
      .
      .
      public function getJSONEncode() {
           return json_encode(get_object_vars($this));
      }
  }
  
  class B {
  
      private $p; //This finally stores objects of class A
      private $q;
      private $r;
  
      public function __construct() {
              $this-&gt;p = array();
      }
  
      public function fn1() {
          ...
      }
  
      public function fn2() {
          ...
      }
  
      .
      .
      .
  
      public function getJSONEncode() {
           return json_encode(get_object_vars($this));
      }
  
  }
  
  class C {
  
      private $arr;
  
      public function __construct() {
              $this-&gt;arr = array();
      }
  
      public function fillData($data) {
          $obj = new B();
          //create objects of class B and fill in values for all variables
          array_push($this-&gt;arr, $obj)
      }
  
      public function returnData() {
            echo $this-&gt;arr[0]-&gt;getJSONEncode(); //Edited to add
  
      }
  
  }
  </code></pre>
  
  <p>What would be the best way to achieve this nested json encoding?</p>
  
  <p>Edited to Add:</p>
  
  <p>The output I get when the returnData method is executed is:</p>
  
  <pre><code>{"p":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}],"q":"Lorem Ipsum","r":"Dolor Sit Amet"}
  </code></pre>