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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class NotSerializable implements Serializable
{
  public function serialize()
  {
    throw new LogicException('You cannot serialize or unserialize NotSerializable instances');
  }

  public function unserialize($serialized)
  {
    throw new LogicException('You cannot serialize or unserialize NotSerializable instances');
  }
}

If you write a test code like this:

1
2
3
4
$a = new NotSerializable();

echo serialize($a);

It will throw the error:

1
2
3
4
5
6
7
PHP Fatal error:  Uncaught LogicException: You cannot serialize or unserialize NotSerializable instances in /home/jdoodle.php:7
Stack trace:
#0 [internal function]: NotSerializable->serialize()
#1 /home/jdoodle.php(23): serialize(Object(NotSerializable))
#2 {main}
  thrown in /home/jdoodle.php on line 7
Command exited with non-zero status 255

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.

Reference

[^1] PHP Serialization, Stack Traces, and Exceptions