Home  >  Article  >  Backend Development  >  PHP magic method __sleep __wakeup (4), __sleep__wakeup_PHP tutorial

PHP magic method __sleep __wakeup (4), __sleep__wakeup_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:03801browse

PHP magic methods __sleep __wakeup(4), __sleep__wakeup

Serialization serialize can convert variables, including objects, into continuous bytes data. You can serialize The variables are stored in a file or transmitted over the network. They are then deserialized back to the original data. PHP can successfully store the properties and methods of its objects before you deserialize the class objects. Sometimes You may need an object to be executed immediately after deserialization. For such purposes, PHP will automatically look for the __sleep and __wakeup methods.

When an object is serialized, PHP will call the __sleep method (if it exists). After deserializing an object, PHP will call the __wakeup method. Neither method accepts parameters. The __sleep method An array must be returned containing the attributes that need to be serialized. PHP will discard the values ​​​​of other attributes. If there is no __sleep method, PHP will save all attributes.


Before the program is executed, the serialize() function will first check whether there is a magic method __sleep. If it exists, the __sleep() method will be called first, Only then the serialization (serialization) operation is performed. This function can be used to clean an object and return an array containing the names of all variables in the object. If the method returns nothing, NULL is serialized, resulting in An E_NOTICE error. In contrast, unserialize() checks whether there is a __wakeup method. If it exists, it will be called first __wakeup method, prepare object data in advance.

__sleep method is often used to submit uncommitted data, or similar operations. Also, if you have some very large objects, No need to save, this function is very useful. __wakeup is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.

<?php
class Connection {
    protected $link;
    private $server, $username, $password, $db;
    
    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }
    
    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this->password);
        mysql_select_db($this->db, $this->link);
    }
    
    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
}
?>

The following example shows how to use the __sleep and __wakeup methods to serialize an object. The Id attribute is a temporary attribute that is not intended to be retained in the object. The __sleep method is guaranteed not to be used in the serialized object. Contains the id attribute. When deserializing a User object, the __wakeup method establishes a new value for the id attribute. This example is designed to be self-sustaining. In actual development, you may find that objects containing resources (such as images or data streams) need these methods.

 <?php
class user {
    public $name;
    public $id;
    
    function __construct() {    // 给id成员赋一个uniq id 
        $this->id = uniqid();
        }
        
    function __sleep() {       //此处不串行化id成员
        return(array('name'));
        }
        
    function __wakeup() {
        $this->id = uniqid();
        }
    }

$u = new user();

$u->name = "Leo"; 

$s = serialize($u); //serialize串行化对象u,此处不串行化id属性,id值被抛弃

$u2 = unserialize($s); //unserialize反串行化,id值被重新赋值

 

//对象u和u2有不同的id赋值

print_r($u);

print_r($u2);

?>

Example 3: A flaw in the __wakeup method needs to be noted. If you plan to unserialize an object, you

 <?php 
class A { 
 public $b; 
 public $name; 
} 

class B extends A { 
 public $parent; 
 public function __wakeup() { 
  var_dump($parent->name); 
 } 
} 

$a = new A(); 
$a->name = "foo"; 
$a->b = new B(); 

//我们期望这里输出:foo,但实际在后面的代码执行之后,实际输出NULL.

$a->b->parent = $a; 
$s = serialize($a); 
$a = unserialize($s); 
?> 

Cause: The $b object is unserialized before $name. So when B::__wakeup is executed, $a->name has not been assigned a value

So, be careful about the order in which you define variables in a class.

Original address: http://blog.sina.com.cn/s/blog_758ddcb90100yk05.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/917484.htmlTechArticlePHP magic method __sleep __wakeup (4), __sleep__wakeup serialization serialize can convert variables, including objects, into continuous bytes data. You can save the serialized variables in a file...
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