📜 ⬆️ ⬇️

Nuances of serialization

I think many people know the "magic" methods __ sleep and __ wakeup to control the serialization of objects.

It would seem simple:
__sleep is called before the serialization so that you can remove unnecessary connections (DB, MemCash, etc.).
__wakeup is called after unserialize, so that the necessary connections can be automatically returned to the backside.

But there is a nuance. And I came across him 4 times in the last 5 years of work.

1. The __sleep method must return an array with a list of properties that need to be serialized.
2. If the object is serialized and then continues to be used, it may be corrupted, since the __sleep method was called during serialization.
')
The example from the manual misleads

public function __sleep ()
{
mysql_close ($ this-> link);
}

Having done everything following the example, not only will the result of serialization be NULL, but the object itself will be corrupted)))

So be careful and carefully read the manual))))

Source: https://habr.com/ru/post/61008/


All Articles