Monthly Archives: March 2009

Unserializing objects from the session in PHP

I’ve had a little trouble unserializing objects that are stored in the session. Here’s the problem :

  1. Request 1 starts
  2. session_start() is called
  3. an object is put on the session
  4. Request 1 ends
  5. Request 2 starts
  6. session_start() is called

… and suddenly, I get the error : __PHP_Incomplete_Class Object…

After a short search, the reason becomes clear : when an object is unserialized, PHP must be able to find the object’s Class. So one way could be including the class manually (e.g. require_once ‘SomeClass.class.php’), but this is very error-prone and just not the way to do it.

The unserialize function will try to find the classes using the __autoload function, or using a custom function you can set using ini_set(‘unserialize_callback_func’, ‘mycallbackfunction’). See the PHP manual for a more extended explanation.

So the clue here is that all serialized classes must be located from the moment the session_start() is called, cause that is when all objects are unserialized from the session !