How to store objects in a session in PHP?

Hello, I would like to save or save an object inside a session using classes such as SessionHandler or $ _SESSION arrays, I saw that this is possible if I serialize the object and I do not want to lose the methods of this instance of the object. I saw that serialization is possible, but the objects that I want to save are created by PDOStatement :: fetchObject (), although the instance class is Users. I get this error:

PDOException: You cannot serialize or fail to initialize PDO instances Why? This is not an instance of PDO.

Sorry I'm Spanish and I don't speak very good English. Thanks

+8
php pdo persistence pdostatement
source share
1 answer

PHP native $_SESSION sessions transparently serialize and unserialize objects that support the PHP serialization protocol or Serializable interface . You do not need to explicitly serialize them.

PHP cannot serialize resources because they are stateful descriptors of a resource outside of PHP control. This is why you cannot serialize PDO or PDOStatement .

By default, an object is serialized by storing all the names and values โ€‹โ€‹of properties that are uneserialized by creating an object with the same class (without calling the constructor) and setting the serialized properties directly. You can customize serialization behavior for your objects using the __sleep and __wakeup magic methods or by implementing the Serializable interface. But not both! If you use implements Serializable , __sleep and __wakeup ignored.

Important note: when using object serialization, you must have a class definition loaded before you unserialize (or have an autoloader that can load it), and it must match the class definition of the object that was serialized. Class definitions are not stored in serialized data.

For example, suppose you have the following:

 class Test { public $version = 1; protected $abc; public function setAbc($abc) { $this->abc = $abc; } } $t = new Test(); $t->setAbc(123); $_SESSION['mytest'] = $t; 

Now imagine that you are changing Test one day to look like this:

 class Test { public $version = 2; private $def; public function setDef ($def) { $this->def = $def; } } 

Now suppose that you loaded into your new code an object serialized when Test was in version 1:

 $t = $_SESSION['mytest']; // this was stored yesterday, when Test was version 1 var_dump($t) 

You will receive the following:

 object(Test)#1 (3) { ["version"]=> int(1) ["def":"Test":private]=> NULL ["abc":protected]=> int(123) } 

In addition, you cannot use the old methods:

 if ($t->version == 1) { // Check for class version $t->setAbc(345); // "Fatal error: Call to undefined method Test::setAbc()" } 
+14
source share

All Articles