[Last Call] Learn how to a build a cloud-first strategyRegister Now


PHP Sessions and custom classes

Posted on 2007-07-29
Medium Priority
Last Modified: 2013-12-12
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.
Question by:natbh
  • 2

Author Comment

ID: 19588900
Nobody knows?

Accepted Solution

maesk earned 1000 total points
ID: 19588929
Maybe you should serialize() the object before storing it in the session variable and then unserialize them again when retrieving it from the session.


Assisted Solution

CosminB earned 1000 total points
ID: 19592413

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.


Author Comment

ID: 19594448
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.  

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question