php 魔术方法合集【一】 - 点滴记忆*记忆点滴
收藏本站

php 魔术方法合集【一】

PHP把所有以__(两个下划线)开头的类方法当成魔术方法。所以当你定义类方法时,除了上述魔术方法,建议不要以 __为前缀。

PHP中被称为"魔术方法"(Magic methods) 有

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state()__clone()


public array __sleep ( void )
void __wakeup ( void )

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


与之相反, unserialize()会检查是否存在一个__wakeup()方法。如果存在,则会先调用 __wakeup方法,预先准备对象需要的资源。

__wakeup()经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作。

例:


<?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();
    }
}
?>


    留下足迹