欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[PHP]实体类基类和序列化__sleep问题

程序员文章站 2022-04-28 14:22:07
1.构造函数传参2.__get和__set实现,当调用不存在的属性的时候,可以取值和赋值到data属性数组3.__sleep实现,当序列化对象的时候,只序列化data属性数组和类内初始化定义的字段4.__isset实现,可以判断属性是否存在,通过判断data属性数组5.toArray方法实现,返回d ......

1.构造函数传参
2.__get和__set实现,当调用不存在的属性的时候,可以取值和赋值到data属性数组
3.__sleep实现,当序列化对象的时候,只序列化data属性数组和类内初始化定义的字段
4.__isset实现,可以判断属性是否存在,通过判断data属性数组
5.toarray方法实现,返回data属性数组
6.记录了构造初始化后,动态添加的属性字段

 

<?php

class sina_data_object
{
    protected $data = array();
    private $changes = array();
    private $newflag = true;
    public function __construct($data = array()){
        if (empty($data)) {
            $this->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
}

*/