Home >Backend Development >PHP Tutorial >Serialization and deserialization of objects in php
* 1. Serialization of objects
* 1. Any value in php can be serialized into a string containing a byte stream representation
* 2. Serialization Objects can be saved to variables or files for easy saving and transmission
//Numeric serialization
$num = 500; echo serialize($num),'<br>';
//String serialization
$name = 'peter'; echo serialize($name),'<br>';
//Array serialization
$course = ['php','mysql','thinkphp']; echo serialize($course),'<br>';
//Boolean serialization
$isPass = true; echo serialize($isPass),'<br>';
//Object serialization: take a database connection class as an example
class Db { //连接参数与返回值 public $db = null; public $host; private $user; private $pass; //构造方法 public function __construct($host='localhost',$user='root',$pass='root') { //类属性初始化 $this->host = $host; $this->user = $user; $this->pass = $pass; //创建对象时自动连接数据库 $this->connect(); } //连接数据库的方法 private function connect() { $this->db = mysqli_connect($this->host,$this->user, $this->pass); } //serialize($obj)序列化的时候,会自动调用__sleep(void) //主要用于对象休眠时的一些清理工作,例如指定哪些属性允许进入到休眠对象的属性序列中 public function __sleep() { //返回由属性名字符串组成的索引数组,指示序列化时要保存的字段名 return ['host','user','pass']; //对于本案例来说,如果连接参数不变的情况下,只要将$this->db保存到对象序列中即可 // return ['db']; } //unserialize()反序列化的时候,会自动调用__wakeup(void) //主要用于唤醒对象时要做的初始化工作,例如本例中的:自动连接数据库 public function __wakeup() { $this->connect(); } } $obj = new Db();
* Characteristics of object serialization:
* 1. Only save the attributes in the object, not the method
* 2. Only save the class name, not the object name
echo serialize($obj);
//In order to demonstrate deserialization, we will Save the serialized object to a variable, of course, you can also save it to a file
$tmp1 = serialize($obj);
//View the serialized variable content, which is the same as the previous serialized content
echo $tmp1;
// Now perform the deserialization operation and take out the object saved in the variable
$tmp2 = unserialize($tmp1);
//Detect whether $tmp2 is an object
echo '<hr>'; echo is_object($tmp2) ? '对象' : '不是'; echo '<hr>';
//Get the attributes and view the database connection object
var_dump($tmp2->db);
The above is the detailed content of Serialization and deserialization of objects in php. For more information, please follow other related articles on the PHP Chinese website!