I re-read many times how the functions of serialize and unserialize work, and the magic methods of __sleep and __wakeup, but I don’t understand why all this is necessary, an example is given in the documentation, which I didn’t explain to me, unfortunately. Tell me, in what situations should this be used?

2 answers 2

This is for cases when you want to work with data as with a string (for example, write an array in a database). This is similar to the json_encode () / json_decode () function. These functions are one way to serialize.

  • I understand, thank you! - Nikita Pavlov
  • You can mark the decision! - Grulex

Sometimes you need to get a hash of the array, for example, using the md5() function (for example, to check if the data in the array has changed or not), but you just won't do it, then serialize() comes to the rescue. Example:

 $array = array(1, 2, 3); md5($array); //Приведет к фатальной ошибке! md5(serialize($array)); //262bbc0aa0dc62a93e350f1f7df792b9 

It also allows you to write an array \ object into a string, which further allows you to write it to a file \ database \ session, etc., and then extract it using unserialize() . It is also possible to use json_encode () - json_decode (), but in theory serialize() will be faster.