PHP object as session variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nobleknight
Forum Newbie
Posts: 1
Joined: Fri Oct 17, 2008 5:51 am

PHP object as session variable

Post by nobleknight »

Hello,

can someone tell me how to pass an object (an instance of a php built-in class) as a session variable?

Thanks
ahowell
Forum Newbie
Posts: 17
Joined: Mon Sep 01, 2008 9:18 pm

Re: PHP object as session variable

Post by ahowell »

Code: Select all

<?php
 
// Insert
$_SESSION['someIdentifier'] = serialize($object);
 
 
 
// Extract
require_once '/path/to/your/class.php';
$object = unserialize($_SESSION['someIdentifier']);
Notes:
- Storing your object in a session, it is no longer an 'instance'. Any changes occurring
to the object after it is serialized will not be contained in the serialized version. Make sure you only
save your objects to the session at the very end of all processing.

- Do not use session.auto_start when storing objects within session. Class files need to be included
before the objects can be brought out of a session. Auto start will take place before you would be able
to include all necessary files.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: PHP object as session variable

Post by VladSun »

Objects stored in $_SESSION variable are serialized automatically. There is no need to use un/serialize() functions.

Code: Select all

$_SESSION['myobject'] = $object;
........
$next_page_var = $_SESSION['myobject'];
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply