Re: When is __destruct called on an object in $_SESSION ?
| From: | Peter Ford | Date: | Thu, 14 May 2009 12:54:06 +0000 |
| Subject: | Re: When is __destruct called on an object in $_SESSION ? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-292568@lists.php.net to get a copy of this message | ||
Stuart wrote:
> 2009/5/14 Peter Ford <pete@justcroft.com>:
>> I'm sure I've seen something about this before, but I can't find it:
>>
>> I'm creating a file which needs to live for the duration of a session, and ONLY
>> the duration of the session.
>> I made a little call which holds the name of the file like this:
>> <?php
>> class __TFR
>> {
>> private $file;
>> public function __construct()
>> {
>> $this->file = '/tmp/'.session_id().'.xml';
>> }
>>
>> public function __get($name)
>> {
>> if ($name=='file') return $this->file;
>> }
>>
>> public function __destruct()
>> {
>> @unlink($this->file);
>> }
>> }
>> ?>
>> So I create an instance of this object and I put a reference to the object in
>> the session:
>>
>> <?php
>> $_SESSION['TFR'] = new __TFR();
>> ?>
>>
>> I was then expecting TFR::__destruct() to only be called when the session was
>> closed, with either a timeout, or a session_destroy() call.
>> But it looks like the object destructor is called at the end of every page.
>> Any ideas about working around that?
>
> The destructor will be called at the end of each page request because
> the object in memory is destroyed.
>
> When the object is serialized you will get __sleep being called, and
> when it's unserialized you'll get __wakeup.
>
> There is no way to detect when a session is destroyed unless you
> implement your own session handler.
>
> -Stuart
>
Oh bother. I guess it's a consequence of the statelessness of the PHP engine.
I thought I might be able to set a flag in __sleep() to indicate that the
session had been serialised rather than destroyed, but __destruct() is called
before __sleep().
I will have to see whether it is worth coding a custom session handler or to
just let the disk fill up... :)
--
Peter Ford phone: 01580 893333
Developer fax: 01580 893399
Justcroft International Ltd., Staplehurst, Kent