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()函数,有的话进行调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值