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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With