[thelist] PHP4 objects and a short introduction

Phil Turmel philip at turmel.org
Sat Jul 1 17:28:33 CDT 2006


Jon Molesa wrote:
> That makes sense and what I suspected. I began thinking last night of
> storing the object in a session variable. I know this is old hat for
> most. And I know that OO was just introduced in PHP4, much improved in
> PHP5. I read differing bits of info on PHP4 ability to store an object in
> the a session variable. But from my own tests in appears unlikely.
>
> if(isset($_SESSION['variable']))
> {
> $variable2 = $_SESSION['variable'];
> }
> else
> {
> $variable2 = new MyClass();
> $_SESSION['variable'] = $variable2;
> }
>
> Subsequent calls to methods of $variable2 fail.
>
> $variable2->MemberMethod();
>
> Perhaps I could just assign the contents of the Class's array to a
> session
> var and only create the object if the session var is empty. Thanks again.
>
> On Fri, 30 Jun 2006, Anthony Baratta wrote:
>
>> Jon Molesa wrote:
>>> Would that create the object $myObject each time or does PHP4
>>> realize that
>>> it has been created previously and just references it? If it does create
>>> the object each time is that the correct way to use objects? Seems that
>>> once it has been created my code should just be able to make use of it.
>>> Similar in nature to session_start() recognizing that a session has
>>> already been created. Could someone please clear this up for me? Thank
>>> you and God bless.
>> Only items stored in the Session Object (and the session object itself)
>> are persistent between page calls. Every other object created within a
>> page is create and destroyed within the context of the page.
>>
>> As soon as the code on a particular page is done, PHP cleans up and
>> throws it all away.
Jon/Anthony,

There's more to it:  ALL variables, including session variables, are
created and destroyed for every page.  When a session is used, PHP
automatically serializes the session variables into a string, then
stores that in a file when the script ends.  When session_start is able
to identify an open sesssion, it retrieves the correct file and
unserializes the string within it.  (This storage mechanism can also be
replaced with a custom one...)

Objects need special handling, as they aren't just their contents.  For
objects to be restored in PHP4, the class definition must come before
the call to session_start.  Also, in PHP5, objects won't be serialized
properly if PHP closes the session itself.  You need to either
explicitly call session_write_close before your script ends, or use a
shutdown handler that calls it.

In any case, more information is here:
http://us2.php.net/manual/en/language.oop.serialization.php
http://us2.php.net/manual/en/function.session-set-save-handler.php

HTH,

Phil



More information about the thelist mailing list