PHP对象序列化和反序列化

序列化

final class Db{
	private $db_host;
	private $db_user;
	private $db_pass;
	public function __construct(array $config){
		$this->db_host = $config['db_host'];
		$this->db_user = $config['db_user'];
		$this->db_pass = $config['db_pass'];
		$this->connectDb();

	}
//填写需要序列化的属性,不写此方法的话,序列化全部属性
	public function __sleep(){
		return ['db_host'];
	}

	private function connectDb(){
		if(!@mysqli_connect($this->db_host,$this->db_user,$this->db_pass))
			die("链接数据库失败");
	}



}
$arr = [
	'db_host'=>'localhost',
	'db_user'=>'root',
	'db_pass'=>'root',

];
 $obj = new Db($arr);
//进行序列化
 $str = serialize($obj);
 //var_dump($str);//O:2:"Db":1:{s:11:"Dbdb_host";s:9:"localhost";}
//存到3.txt中 
file_put_contents("3.txt", $str);

3.txt 直接打开显示:㩏㨲䐢≢ㄺ笺㩳ㄱ∺䐀b扤桟獯≴猻㤺∺潬慣桬獯≴紻

用sublime打开显示:

4f3a 323a 2244 6222 3a31 3a7b 733a 3131
3a22 0044 6200 6462 5f68 6f73 7422 3b73
3a39 3a22 6c6f 6361 6c68 6f73 7422 3b7d

 

反序列化对象:

final class Db{
	private $db_host;
	private $db_user;
	private $db_pass;
	public function __construct(array $config){
		$this->db_host = $config['db_host'];
		$this->db_user = $config['db_user'];
		$this->db_pass = $config['db_pass'];
		$this->connectDb();

	}


	public function __wakeup(){
		$this->db_user = 'root';
		$this->db_pass = 'root';
		$this->connectDb();
	}

	private function connectDb(){
		if(!@mysqli_connect($this->db_host,$this->db_user,$this->db_pass))
			die("链接数据库失败");
	}



}
$arr = [
	'db_host'=>'localhost',
	'db_user'=>'root',
	'db_pass'=>'root',

];

$str = file_get_contents('3.txt');
$a = unserialize($str);
var_dump($a);

如果没有weakup()结果是:

object(Db)[1]
  private 'db_host' => string 'localhost' (length=9)
  private 'db_user' => null
  private 'db_pass' => null
有weakup()结果是:
object(Db)[1]
  private 'db_host' => string 'localhost' (length=9)
  private 'db_user' => string 'root' (length=4)
  private 'db_pass' => string 'root' (length=4)

成功的重新构造对象后调用__weakup(){}

unseralize()方法调用前,首先看看有没有weekup()函数,有的话进行调用。

你可能感兴趣的:(php)