The question I have
I was reading this article “PHP Serialization, Stack Traces, and Exceptions”[^1] and had these questions:
- Why PDO isn’t serializable?
- Why isn’t every type of object serializable?
The answer
After some search, I found some useful information as follows. check this for details
A PDO object contains state that cannot be represented in the serialization format. For example, the PDO object contains an open connection to a database server.
And I copied the answer from here:
Some objects encapsulate resources like file pointers or network sockets that can’t be deserialized to the state they were in when you serialized the object that contained them.
Example: you shouldn't deserialize an object that serves as an authenticated database connection, because to do so, you'd need the serialized form to contain a plaintext password. This would not be a good practice, because someone might get a hold of the saved serialized form. You also have no idea when you deserialize that the database server is still running, can be accessed, the authentication credentials still valid, etc.
Why the test written by the author can work
Test code is here:
|
|
If you write a test code like this:
|
|
It will throw the error:
|
|
My understanding
Because the serialize()
function should return string or null to represent the object’s state, but it throws an Exception which isn’t it’s state. Thus in this scenario the object of class NotSerializable
is not serializable even though it implements the Serializable
interface.