• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

PHP Sessions and custom classes

I need to store objects from a class that I wrote in a session, what's the trick?  My class works fine, and I can create an object and store it as a session variable, but I can't use the object's functions  in the session variable.
  • 2
2 Solutions
natbhAuthor Commented:
Nobody knows?
Maybe you should serialize() the object before storing it in the session variable and then unserialize them again when retrieving it from the session.


This happens because your class definition is not available when the session data is deserialized.
You should have the class definition loaded before session_start() is called, so your code should look like:
require 'path/to/my_class.php';

Another solution would be to use the "unserialize_callback_func" directive. This is from the php manual(http://www.php.net/manual/en/function.unserialize.php):

unserialize_callback_func directive:  It's possible to set a callback-function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess to define 'unserialize_callback_func'. Everytime an undefined class should be instantiated, it'll be called. To disable this feature just empty this setting.

natbhAuthor Commented:
Thank you both for the suggestions, I don't have time at the moment to check to see if they work, but when I do, I'll award the points.  
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now