Home > Article > Backend Development > What does php serialization mean?
Serialization is the process of converting variables into strings that can be saved or transmitted; deserialization is to convert this string into the original variable at the appropriate time for use. These two processes combine to easily store and transfer data, making the program more maintainable.
Serialization and deserialization in PHP can be achieved through the functions serialize() and unserialize() respectively.
string serialize ( mixed value )
serialize() returns a string, which contains a byte stream representing value and can be stored anywhere. (Recommended learning: PHP Programming from Beginner to Master)
This is helpful for storing or transferring PHP values without losing its type and structure.
If you want to change the serialized string back to PHP value, you can use unserialize(). serialize() can handle any type except resource. You can even serialize() arrays that contain references to themselves. References in the array/object you are serializing() will also be stored.
When serializing an object, PHP will attempt to call the object's member function __sleep() before the sequence action. This allows any cleanup operations to be done before the object is serialized. Similarly, when an object is restored using unserialize(), the __wakeup() member function will be called.
Note: In PHP 3, object properties will be serialized, but methods will be lost. PHP 4 breaks this limitation and can store both properties and methods. See the Serialized Objects section in Classes and Objects for more information.
serialize() Example
<?php // $session_data 是包含了当前用户 session 信息的多维数组。 // 我们使用 serialize() 在请求结束之前将其存储到数据库中。 $conn = odbc_connect ("webdb", "php", "chicken"); $stmt = odbc_prepare ($conn, "UPDATE sessions SET data = ? WHERE id = ?"); $sqldata = array (serialize($session_data), $PHP_AUTH_USER); if (!odbc_execute ($stmt, &$sqldata)) { $stmt = odbc_prepare($conn, "INSERT INTO sessions (id, data) VALUES(?, ?)"); if (!odbc_execute($stmt, &$sqldata)) { /* 出错 */ } } ?>
The above is the detailed content of What does php serialization mean?. For more information, please follow other related articles on the PHP Chinese website!