Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
bobobobo Avatar asked Jan 29 '11 04:01

bobobobo


2 Answers

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.

like image 87
New Guy Avatar answered Oct 19 '22 02:10

New Guy


Could you maybe use var_export? I only just learned about it today, so maybe it's not really that relevant.

like image 1
sdleihssirhc Avatar answered Oct 19 '22 03:10

sdleihssirhc