マジックメソッド_sleepと_wakeup
1539 ワード
, json_encode json_decode , , 、 。json ,
<?php
/**
* __sleep() __wakeup()
* __sleep(): serialize() , 。 ,
* __wakeup():unserialize() , ,
*/
class Test{
public $s = 'hehe';
public $a = 'world';
public function __sleep(){
return array('a');// a
}
public function __wakeup(){
$this->a = 'hello';// a
}
}
$m = new Test();
$n = serialize($m);
$m = unserialize($m);
var_dump($m);
?>
下を見る_sleep __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();
}
}
?>