php魔术方法__sleep() 和 __wakeup()

时间:2014-10-29 22:26:33   收藏:0   阅读:229

魔术方法的使用

<?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()
    {
        echo __METHOD__;
        return array(‘server‘, ‘username‘, ‘password‘, ‘db‘); //序列化时保存这些属性
    }
    
    public function __wakeup()
    {
        $this->connect(); //反序列化后自动连接数据库
        echo __METHOD__;
    }
}

$conn = Connection(‘mysql://localhost:3306/‘,‘root‘,‘root123‘,‘db_php‘);

unserilize(serialize($conn));

?>

输出

__sleep__wakeup


评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!