Page 1 of 1
Help: Arrays of Objects as Session Variables
Posted: Tue Sep 03, 2002 4:44 pm
by bhack
Hello there,
I'm having trouble passing the contents of an object between functions. Specifically, I have a dynamic array of objects populated in one function. I have tried registering the array (or a single object) as a session variable, and then printing out (or using) the contents in a separate function.
Any ideas or examples?
Thanks,
Byron

Posted: Tue Sep 03, 2002 4:51 pm
by JPlush76
how about posting your code so we can take a look?

Posted: Tue Sep 03, 2002 9:12 pm
by nielsene
Objects will not work as session variables unless you setup object
serialization using
__wake and __sleep.
Posted: Wed Sep 04, 2002 1:33 am
by Takuma
I don't get serialise()... and don't know when to use it.
Posted: Wed Sep 04, 2002 10:18 am
by Tzicha
Not true. One can use objects as session variables without using the serializing functions. To use objects this way requires that one include the class (object) definition before using the session stored object.
-=A little clarification, according the the PHP manual (and this only applies the PHP 4+):
If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.
It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class stdClass without any functions available at all, that is, it will become quite useless.
=-
Thus
file: sample.class.php
Code: Select all
<?php
class Sample{
function Sample(){
$this->test = 'My Test';
}
}
?>
file: index.php
Code: Select all
<?php
include_once('sample.class.php');
session_start();
$test =& new Sample();
echo $test->test;
$_SESSIONї'test'] =& $test; //for PHP 4.2+
?>
file: page_2.php
Code: Select all
<?php
include_once('sample.class.php');
//You must include the class definition before starting the session
//or using the session object variable
session_start();
echo $_SESSIONї'test']->test;
?>
As for the original question, some sample of the problematic code would be helpful. If the object instance is being accessed without actually being passed to the function, that can be the problem (a variable scope issue). If it is accessed from the $_SESSION variable then you might have other problems.