php类知识---最疯狂的魔术方法serialize,_sleep,__wakeup,unserialize,__autoload,__clone

  • serialize-----把实例化的对象写入文件
  • __sleep 调用serialize时触发
<?php

class mycoach
{
    public function __construct($name,$age,$expertin=[]){

        $this->name = $name;
        $this->age = $age;
        $this->expertin=[];
        $this->expertin=$expertin;
    }

    public function __sleep()
    {
        return ['name','age','expertin'];
    }
}

$cpc = new mycoach('陈培昌',22,['散打','泰拳', '巴西柔术']);
$srobj = serialize($cpc);
file_put_contents('cpcssecret.txt',$srobj);
?>

关键要点:
----类内部实现的 __sleep()要返回数组数据结构,元素都来自类的属性,以此达到控制哪些类可以写入文件
----serialize方法以对象为参数,返回值就是要写入文件的数据。
生成的文件中记录的对象形如:
O:7:"mycoach":3:{s:4:"name";s:9:"陈培昌";s:3:"age";i:22;s:8:"expertin";a:3:{i:0;s:6:"散打";i:1;s:6:"泰拳";i:2;s:12:"巴西柔术";}}
 
  • unserialize-----把文件中的记录还原为类的实例对象
  • __wakeup------执行unserialize时调用,用于执行一些初始化操作
<?php

class mycoach
{
    public function __construct($name,$age,$expertin=[]){

        $this->name = $name;
        $this->age = $age;
        $this->expertin=[];
        $this->expertin=$expertin;
    }

    public function __sleep()
    {
        return ['name','age','expertin'];
    }

    public function __wakeup()
    {
        #用途:还原对象(反序列化)的时候,执行一些初始化操作
        echo "还原为对象"."\n";

    }
}

$objdate = file_get_contents('cpcssecret.txt');
var_dump(unserialize($objdate));
?>

输出结果:
还原为对象
object(mycoach)#1 (3) {
  ["name"]=>
  string(9) "陈培昌"
  ["age"]=>
  int(22)
  ["expertin"]=>
  array(3) {
    [0]=>
    string(6) "散打"
    [1]=>
    string(6) "泰拳"
    [2]=>
    string(12) "巴西柔术"
  }
}
  • clone复制对象属性
  • __clone可以限制哪些属性可以复制,哪些属性采用自定义
  • __autoload 唯一在类定义体外使用的方法

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/10960865.html
今日推荐