Hello I would like to store or save an object inside a session, using classes like SessionHandler or arrays $_SESSION,I’ve seen that it is possible if I serialize the object, and I don’t want to lose the methods of that object instance.
I’ve seen serializing is possible but the object I want to store is created by PDOStatement::fetchObject() although the instance class is Users I get this error:
PDOException: You cannot serialize or unserialize PDO instances
Why? It is not a PDO instance..
Sorry I am Spanish and I don’t speak English very well..
Thanks
PHP’s native
$_SESSIONsessions transparently serialize and unserialize objects that support PHP’s serialization protocol or theSerializableinterface. You do not need to explicitly serialize them.PHP cannot serialize
resourcesbecause these are handles to some stateful resource outside PHP’s control. This is why you cannot serializePDOorPDOStatementobjects.By default an object is serialized by saving all property names and values and unserialized by creating an object with the same class (without invoking the constructor) and directly setting the serialized properties. You can customize serialization behavior for your objects using the
__sleepand__wakeupmagic methods or by implementing theSerializableinterface. But not both! If you useimplements Serializable,__sleepand__wakeupare ignored.One important note: when using object serialization, you must have the 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 the serialized data.
For example suppose you have the following:
Now imagine you change
Testone day to be like this instead:Now suppose you load into your new code an object serialized when
Testwas at version 1:You will get this:
Furthermore, you can’t use old methods: