PHP magic method: __sleep __wakeup

WBOY
Release: 2016-08-08 09:33:09
Original
1513 people have browsed it

From php5 and later versions, classes can use magic methods. PHP stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that function names do not start with __ unless it is to overload existing magic methods.

The existing magic methods in PHP include __construct, __destruct, __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state and __clone.

Let’s talk about __sleep __wakeup in the PHP magic method:

Serialize can convert variables, including objects, into continuous bytes data. You can store the serialized variables in a file or transmit them over the network. Then deserialize and restore them to the original data. You are deserializing For a class defined before serializing its objects, PHP can successfully store its object's properties and methods. Sometimes you may need an object to be executed immediately after deserialization. For such purposes, PHP will automatically look for __sleep and __wakeup method.

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


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.

The __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();
    }
}
?>
Copy after login

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 guarantees that the id attribute is not included in the serialized object. When To deserialize 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) require 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);

?>
Copy after login

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); 
?> 
Copy after login

Reason: 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 your class.


The above introduces the PHP magic method: __sleep __wakeup, including the content of PHP magic method. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!