<?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:"巴西柔术";}}
<?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) "巴西柔术"
}
}