10.7 Using Objects As Session Variables


10.7 Using Objects As Session Variables

You're having trouble loading objects from sessions.

Technique

Remember that you must always include the class definition in every place you use the object.

std_class.inc:

 <?php // // File:  std_class.inc //   Contains the class definition necessary to let an object be a session //   variable. // class Foo {     var $name;     var $email;     //     // A simple function to illustrate the point     //     function normalize_name ()     {         $name = preg_replace("/h(.)+/i", "\1", $this->name);         return substr($name, 0, 15);     } } ?> 

main.php:

 <?php // //  File:  main.php //    Here is where we save and retrieve the object // include_once 'std_class.inc'; session_register('foobar'); if (!$foobar) {     $foobar = new Foo;     $foobar->name = "Sterling Hughes";     $foobar->email = "sterling@php.net";     $foobar->normalize_name(); } ?> <a href="nextPage.php">Click Here</a> 

nextPage.php:

 <?php // //  File: nextPage.php //    Print out the name without initializing the //    class and setting the variables // include_once 'std_class.inc'; session_register('foobar'); print $foobar->name; ?> 

Comments

At the time of this writing, for PHP's session module to work properly with objects, you must include the class definition before you start the session. This needs to be done for every object stored in the session. This might change in later versions of PHP, but right now it is required. If you don't include the class definition, every time you access an object's property or method, PHP will print a warning saying that you should include class definition first.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net