PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

An Introduction To PHP Sessions

Can I Store An Object In A Session?

Yes, using the following code we can include our class file as we would for any class. In page1.php we will instantiate a new object and put it in a session variable. Let’s us create a simple class file to include in our page1.php and page2.php scripts, we shall call it myclass.php.

Listing 15 myclass.php
<?php
// our class
class mySessionClass{
 
// The constructor, duh!
function __construct(){
}
 
// a function to set a property
function bar(){
  return 'foo';
}
 
} // end of class
?>

In page1.php we include the class file and instantiate a new instance of the class directly into a session variable.

Listing 16 page1.php
<?php
// include the class file
include('myclass.php');
 
// begin the session
session_start();
 
// instantiate a new instance of the class mySessionClass
$_SESSION['foo']= new mySessionClass;
 
// echo a little message to say it is done
echo 'Setting value of foo to an object';
?>

Now we have the object in a session variable, we can go on to page2.php and use methods from mySessionClass.

Listing 17 page2.php
<?php
 
// include the class file
include('myclass.php');
 
// begin the session
session_start();
 
echo $_SESSION['foo']->bar();
?>

Important Note: You MUST include the class definition on every page when you store an object

In This Article