1.构造函数传参
2.__get和__set实现,当调用不存在的属性的时候,可以取值和赋值到data属性数组3.__sleep实现,当序列化对象的时候,只序列化data属性数组和类内初始化定义的字段4.__isset实现,可以判断属性是否存在,通过判断data属性数组5.toArray方法实现,返回data属性数组6.记录了构造初始化后,动态添加的属性字段
newFlag = true; } else { $this->newFlag = false; foreach ($data as $k => $v) { $this->data[$k] = $v; } } } public function __isset($name){ return isset($this->data[$name]); } public function __get($name){ if(!array_key_exists($name, $this->data)){ return null; } return $this->data[$name]; } public function __set($name, $value){ $this->data[$name] = $value; if (!$this->newFlag) { $this->changes[$name] = $value; } } public function __sleep(){ return array('data'); } public function toArray(){ return $this->data; } public function isNew(){ return $this->newFlag; } public function clearNewFlag(){ $this->newFlag = false; } public function isModified() { return (!empty($this->changes)); } public function getChanges() { return $this->changes; } public function clearChanges() { $this->changes = array(); } }class Setting extends Sina_Data_Object{ const STATUS=1; public $other='aaa'; public function __construct($data=array()){ parent::__construct($data); }}//初始化对象$data=array('user'=>'taoshihan');$setting=new Setting($data);//动态增加属性$setting->age=100;var_dump($setting);/*object(Setting)#1 (4) { ["other"]=> string(3) "aaa" ["data":protected]=> array(2) { ["user"]=> string(9) "taoshihan" ["age"]=> int(100) } ["changes":"Sina_Data_Object":private]=> array(1) { ["age"]=> int(100) } ["newFlag":"Sina_Data_Object":private]=> bool(false)}*///动态改变初始化的字段$setting->other='bbbb';//序列化对象$serializeSetting=serialize($setting);//反序列化对象$setting2=unserialize($serializeSetting);var_dump($setting2);/*object(Setting)#2 (4) { ["other"]=> string(3) "aaa" ########反序列化回来这里还是aaa ["data":protected]=> array(3) { ["user"]=> string(9) "taoshihan" ["age"]=> int(100) } ["changes":"Sina_Data_Object":private]=> array(0) { ##########change属性里面的数据没有序列化进去 } ["newFlag":"Sina_Data_Object":private]=> bool(true) #########反序列化回来这里是true}*/