Putting Object In Session [PHP]

Using the following code construct we can put an object in a session variable in PHP. Let’s us create a simple class file c1.php and two php scripts 1.php and 2.php to demonstrate this.

c1.php:

<?php
class c1
{
public $v1=10.5;
private $v2=20;
protected $v3=30;
public $v4="a string";
function f1()
{
echo "<script>alert('class function f1() called.')</script>";
}
}
?>

In 1.php we include the class file c1.php either using __autoload() function or using include() and instantiate a new instance of the class directly into a session variable or assign a named object into a session variable. 

1.php:

<?php
function __autoload($class)
{
include_once($class.".php");
}

$obj1_c1=new c1();//$obj_c1 is a named object

session_start();
$_SESSION['obj1_c1']=$obj1_c1;
echo "object in session. Now open 2.php"
?>

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

2.php:

<?php
function __autoload($class)
{
include($class.".php");
}
session_start();
$obj1_c1=$_SESSION['obj1_c1'];
echo $obj1_c1->v1;
$obj1_c1->f1();
?>

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

Advertisements

2 thoughts on “Putting Object In Session [PHP]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s