PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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


Tagged in ,