- 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 "还原为对象"."
";
}
}
$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可以限制哪些属性可以复制,哪些属性采用自定义
<?php
class bt
{
protected $master = "徐晓冬";
private $age;
public function __construct($name,$srcfrom)
{
echo "欢迎来到必图拳馆,我是徐晓冬";
$this->name = $name;
//$this->age = $age;
$this->srcfrom = $srcfrom;
}
public function __get($master)
{
return $this->$master;
}
public function __set($key,$value)
{
$this->$key = $value;
}
public function self_introduce()
{
echo "大家好,我是 ".$this->name. " 今年芳龄 ". $this->age." 来自 ". $this->srcfrom." 我师父是 ".$this->master."
";
}
public function __clone()
{
$this->name = '丁大锅';
$this->age = 34;
$this->srcfrom = '维基泄密';
}
}
/*$zilong = new bt('吴紫龙',21,'公安大学','徐晓冬');*/
$zilong = new bt('紫龙','公安大学');
$zilong->age=33;
$zilong->self_introduce();
$dy = clone $zilong;
$dy ->self_introduce();
<?php
function __autoload($name)
{
echo "this one ".$name;
include($name.".php");
}
$cpc = new bt('程劲','塔沟武校');
var_dump($cpc);
?>
输出结果:
this one bt欢迎来到必图拳馆,我是徐晓冬object(bt)#1 (4) {
["master":protected]=>
string(9) "徐晓冬"
["age":"bt":private]=>
NULL
["name"]=>
string(6) "程劲"
["srcfrom"]=>
string(12) "塔沟武校"
}