I am having trouble with the following code example which uses sessions to store a PHP class object on one page and refers to that object on a second page. My simple example is listed below. When I run this via xampplite, the first page displays fine and creates the object, when I click on the Page 2 link, the second page loads, retrieves the object from the $_SESSION array, but generates the following error.
Object passed via $_SESSION
Fatal error: main() [<a
href='function.main'>function.main</a>]: The script
tried to execute a method or access a property of an
incomplete object. Please ensure that the class
definition "Myclass" of the object you are
trying to operate on was loaded _before_ unserialize()
gets called or provide a __autoload() function to load
the class definition in
C:\XAMPP\xampplite\htdocs\MyClassPage2.php on line 17
Any thoughts?
Myclass.class.php
PHP Code:
class Myclass
{
public $var;
function __construct()
{
$this->var = 'Hello from ';
}
function echo_var()
{
echo $this->var . $_SERVER['PHP_SELF'] . '<br />';
}
}
page1.php
PHP Code:
include './Myclass.class.php';
session_start();
if (isset($_SESSION['newobj'])) {
$newobj = $_SESSION['newobj'];
echo 'Object passed via $_SESSION<br />';
} else {
$newobj = new Myclass;
$_SESSION['newobj'] = $newobj;
echo 'Object created with <I>new</I><br />';
}
$newobj->echo_var();
echo '<a href="page2.php">Page 2</a>';
page2.php
PHP Code:
include './Myclass.class.php';
session_start();
if (isset($_SESSION['newobj'])) {
$newobj = $_SESSION['newobj'];
echo 'Object passed via $_SESSION<br />';
} else {
$newobj = new Myclass;
$_SESSION['newobj'] = $newobj;
echo 'Object created with <I>new</I><br />';
}
$newobj->echo_var();
echo '<a href="page1.php">Page 1</a>';