[PHP] 魔術方法__get __set __sleep __wakeup的實際使用

1.__get __set是在給不可訪問屬性賦值和讀取時,調用php

2.__sleep 是在序列化對象的時候調用函數

3.__wakeup是在反序列化對象的時候調用this

4.能夠在序列化對象的時候 , 只序列化指定的屬性 , 減小序列化後的大小, 要把這個對象字符串存儲在好比memcache的時候 ,比較有用code

 5.好比下面的例子 , 我只序列化了data屬性 , 在__sleep函數裏進行限制對象

<?php
class Test{
	public $name;
	protected $data=array();
	public function __set($name,$value){
		$this->data[$name]=$value;
	}
	public function __get($name){
		if(!isset($this->data[$name])){
			return "";
		}
		return $this->data[$name];
	}
	public function __sleep(){
		echo "sleep...\r\n";
		return array('data');
	}
	public function __wakeup(){
		echo "wakeup...\r\n";
	}
}
$test=new Test();
$test->name="我不會被序列化進去";
$test->bbbb="taoshihan";


$testObjectStr=serialize($test);
var_dump($testObjectStr);
var_dump(unserialize($testObjectStr));

  

 

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息