Home  >  Article  >  Backend Development  >  How to use php serialize()

How to use php serialize()

青灯夜游
青灯夜游Original
2021-10-15 17:31:162197browse

In PHP, serialize() is used to serialize an object or array and convert it into a string that can be stored. The syntax is "serialize($value)". After using the serialize() function to serialize an object, you can easily pass it to other places that need it, and its type and structure will not change.

How to use php serialize()

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php serialize() Function

serialize() function is used to serialize an object or array, convert it into a string that can be stored and return it.

Take objects as an example. When serializing an object, all variables of the object will be saved, but the methods of the object will not be saved, only the name of the class will be saved. Additionally, in order to be able to deserialize an object, the object's class must have been defined. If you serialize an object of class A, a string related to class A will be returned that contains the values ​​of all variables in the object. The syntax format of

serialize() function is as follows:

serialize($value)
  • $value: The variable to be serialized.

The serialize() function can handle any type except resource. When serializing an object, PHP calls the object's __sleep() member function before the sequence action. This allows any cleanup operations to be done before the object is serialized. Similarly, when an object is deserialized using unserialize(), the __wakeup() member function is called.

[Example] Use the serialize() function to serialize an object.

<?php
header("Content-type:text/html;charset=utf-8");
class WebSit {
	public $name;
	public $url;
	function __construct($name, $url) {
		$this -> name = $name;
		$this -> url = $url;
	}

}

$websit = new WebSit(&#39;PHP中文网&#39;, &#39;https://www.php.cn/&#39;);
$ser_str = serialize($websit);
echo $ser_str;
?>

The running results are as follows:

How to use php serialize()

Note: If you want to change the serialized string back to a PHP value, you can use unserialize().

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to use php serialize(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn