Re: How to preserve instance of class within sessions ???

From: Date: Thu, 08 May 2003 09:00:40 +0000
Subject: Re: How to preserve instance of class within sessions ???
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-146804@lists.php.net to get a copy of this message
At 10:18 08.05.2003, aka MacGuru said: --------------------[snip]-------------------- >I have class CMyApp which stores a lot of app data (like persistent >database connections via ADODB), and instance of this class called >$gApp (of course, as global). I am using "register globals off" and >trying to preserve $gApp through entire execution flow of the program. > >However, as I am understood from the manual, objects cannot be >preserved via session SID data, neither the object is alive in $GLOBALS >after header("Location: script.php") with SID (not shown there). > >As a dubious solution I can write two functions which extract object's >fields into plain variables, put them into global scope, and then >recreating object back from saved global data. However, this is kinda >awkward. > >The questions is how to preserve instance of the class within sessions >(if it is possible at all, of course) with "register globals off" (or >at least, how to turn register globals on ONLY for my program, and not >for any other php app). --------------------[snip]-------------------- First of all, read the manual pages on sessions thoroughly. $_GLOBALS are never preserved across a session, that's what $_SESSION is for. And yes, you _can_ make objects session persistent, PROVIDED that the necessary class definitions are loaded/included/defined _before_ the session gets reconstructed. Working example: class A { function A() { $this->time = time(); } function say() { return date('H:m:s', $this->time); } } session_start(); if (!$_SESSION['instance_A']) $_SESSION['instance_A'] = new A(); $a =&$_SESSION['instance_A']; echo 'The object's time is ', $a->say(), '<br />'; If however you would put session_start() before the class definition, or have session.auto_start enabled in php.ini, this cannot work - PHP needs to know the class definition when reconstructing an object from session data. If this is missing it will resort to a default class where all data properties are preserved, but of course no methods are available. -- >O Ernest E. Vogelsinger (\) ICQ #13394035 ^ http://www.vogelsinger.at/

« previous php.general (#146804) next »