title: PHP: array of objects - serialize vs json_encode - alternatives?
body: <p>In PHP I'm having a real hard time using <code>serialize</code>/<code>unserialize</code> on a large array of objects (100000+ objects). These objects can be of a lot of different types, but are all descendants from a base class.</p>
  
  <p>Somehow when I use <code>unserialize</code> on the array of objects about 0,001% of the objects are generated wrong! A whole different object is generated instead.   This does not happen random, but each time with the same objects. But if I change the order of the array, it happens with different objects, so this looks like a bug to me.</p>
  
  <p>I switched to <code>json_encode</code>/<code>json_decode</code>, but found that this always uses <code>stdClass</code> as the object's class. I solved this by including the classname of each object as a property, and then use this property to construct a the new object, but this solution is not very elegant.</p>
  
  <p>Using <code>var_export</code> with <code>eval</code> works fine but is about 3 times slower than the other methods and uses much more memory.</p>
  
  <p>Now my questions are :</p>
  
  <ul>
  <li>what could cause the bug / wrong objects that are created with
  <code>unserialize</code> ?</li>
  <li>is there a better way to use <code>json_decode</code> with an array of objects, so that classes are somehow stored within the json
  automatically?</li>
  <li>is there maybe even an other method to read/write a large array of objects in PHP?</li>
  </ul>
  
  <p><em><strong>UPDATE</em></strong></p>
  
  <p>I'm beginning to believe there must be something strange with my array-data, because with <code>msgpack_serialize</code> (php extension, alternative to <code>serialize</code>) I get the same kind of errors  (but strangely enough <strong>not</strong> the same objects are generated wrong!).</p>
  
  <p><em><strong>UPDATE 2</em></strong></p>
  
  <p>Found a solution : instead of doing <code>serialize</code> on the entire array, I do it on each <em>object</em> now, first <code>serialize</code> and then <code>base64_encode</code> and then I store each serialized object as a separate line in a text-file. This way I can generate the entire array of objects and then iterate each object using <code>file()</code> with <code>unserialize</code> and <code>base64_decode</code>  : no more errors!</p>