php saving object in session
I'm trying to save an object in $_SESSION
, but the following:
<?php
$user = db->load( $username, $pass ) ;
$_SESSION[ 'user' ] = $user ;
# on subsequent page loads:
$user = $_SESSION[ 'user' ] ; #retrieve the user from session
Unfortunately this doesn't work.
The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "User" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition
Unless you use serialize():
<?php
$user = db->load( $username, $pass ) ;
$_SESSION[ 'user' ] = serialize( $user ) ;
# on subsequent page loads:
$user = unserialize( $_SESSION[ 'user' ] ) ; #retrieve the user from session
I'm assuming a serialize is required because Session info is saved开发者_如何转开发 out to disk. But shouldn't PHP be smart enough to serialize stuff on its own?
And with the use of serialize/_unserialize_, is this going to work now reliably? Or do I need a __serialize()
method in my PHP class?
You would need the __serialize()
in your class if your object needs to perform some action before being serialized. For instance if it had a reference to an open file and that file needed to be properly closed before serializing.
Could you maybe use var_export? I only just learned about it today, so maybe it's not really that relevant.
As far as the php compiler is concerned all you are doing is writing an object (serialised) to an Array its a different process that ensures $_SESSION is available on the next page. Serialisation is nothing to do with being written to disk more to do with memory as the memory allocated to various methods on your object will not be available on the next page. Serialisation is how PHP holds onto objects accross pages, and you have to do it yourself.
Better Use
json_encode() json_decode()
Probably the best approach this days is to implement Serializable interface with your class.
精彩评论