title: PHP json_encode a debug_backtrace() with resource types
body: <p>Currently, I have a logger which logs errors together with a backtrace.
  The logger serializes the backtrace to JSON via <code>json_encode()</code>.</p>
  
  <p>Let's look at some hypothetical code...</p>
  
  <pre><code>&lt;?php
      error_reporting(-1);                          // show all errors
      function test($b){
          echo json_encode(debug_backtrace());      // take a backtrace snapshot
      }
      $c = imagecreate(50,50);                      // create a resource...
      test($c);                                     // ...and pass to function
  ?&gt;
  </code></pre>
  
  <p>If you <a href="http://codepad.viper-7.com/ch6gVw" rel="nofollow">run the code above</a>, we will see something like:</p>
  
  <blockquote>
    <p><strong>Warning:</strong> json_encode() [function.json-encode]: <strong>type is unsupported, encoded as null</strong> in /code/ch6gVw on line 5
    [{"file":"/code/ch6gVw","line":8,"function":"test","args":[null]}]</p>
  </blockquote>
  
  <p>We can notice two things going on here:</p>
  
  <ol>
  <li>The logger itself is causing a warning! Bad bad bad!</li>
  <li>The logged data tells us we passed a null to the function?!?!</li>
  </ol>
  
  <hr>
  
  <p><strong>So, my proposed solution is something like:</strong></p>
  
  <pre><code>foreach($trace as $i=&gt;$v)
      if(is_resource($v))
          $trace[$i] = (string)$v.' ('.get_resource_type($v).')';
  </code></pre>
  
  <p>The result would look like <code>Resource id #1 (gd)</code></p>
  
  <hr>
  
  <p><strong>This, however, may cause some grave issues.</strong></p>
  
  <ol>
  <li>We need to somehow track which arrays we looped through so as to avoid ending up in infinite loops with arrays referencing themselves (<code>$GLOBALS</code> tend to cause this mess).</li>
  <li>We would also have to convert resources of object properties, but objects, unlike arrays, are not a copy of the original thing, hence changing the property changes the live object. On the other hand, how safe is it to <code>clone()</code> the object?</li>
  <li>Won't such a loop severely slow down the server (backtraces tend to be large, no)?</li>
  </ol>