Home > Backend Development > PHP Tutorial > php 魔术方法 sleep() wakeup()

php 魔术方法 sleep() wakeup()

WBOY
Release: 2016-06-23 13:24:33
Original
1513 people have browsed it

__sleep() 和 __wakeup()

public array __sleep ( void )

void __wakeup ( void )

serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在,该方法会先被调用,然后才执行序列化操作。此功能可以用于清理对象,并返回一个包含对象中所有应被序列化的变量名称的数组。如果该方法未返回任何内容,则 NULL 被序列化,并产生一个 E_NOTICE 级别的错误。

 

示例:

 class user {    public $name;    public $id;    function __construct() {    // 给id成员赋一个uniq id         $this->id = 'asas';    }    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

结果:

user Object ( [name] => Leo [id] => asas ) user Object ( [name] => Leo [id] => 5621ed9f6614c )

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