序列化:
<?php
header('Content-Type:text/html;charset=utf-8');
class Humanity {
public $name;
public $sex;
public $iq=10;
const BIRTHPLACE='地球';
public function eat($food){
echo "{$this->name}正在吃{$food}!";
}
}
$hanMM=new Humanity();
$hanMM->name='韩梅梅';
$hanMM->sex='女';
//对象的序列化 ,对象转换成 字符串!
echo serialize($hanMM);
反序列化:
<?php
header('Content-Type:text/html;charset=utf-8');
class Humanity {
public $name;
public $sex;
public $iq=10;
const BIRTHPLACE='地球';
public function eat($food){
echo "{$this->name}正在吃{$food}!";
}
}
$hanMM=new Humanity();
$hanMM->name='韩梅梅';
$hanMM->sex='女';
//对象的序列化 ,对象转换成 字符串!
$a='O:8:"Humanity":3:{s:4:"name";s:9:"韩梅梅";s:3:"sex";s:3:"女";s:2:"iq";i:10;}';
$asa=unserialize($a);
$asa->eat("鸡肉");
解析:
反序列化注意两点:
序列化后的要用单引号包括起来.
反序列化后要赋值,后调用才能见效果
构造函数+析构函数:
解析:
构造函数是初始化时调用,析构函数是对象销毁是调用.
<?php
header('Content-Type:text/html;charset=utf-8');
class Humanity {
public $name;
public $sex;
public $iq=10;
const BIRTHPLACE='地球';
//构造函数
public function __construct($name,$sex){
$this->name=$name;
$this->sex=$sex;
}
public function eat($food){
echo "{$this->name}正在吃{$food}!";
}
//这个函数在该类的实例被销毁时自动调用
public function __destruct(){
echo "<p>{$this->name}被销毁啦!</p>";
}
}
$hanMM=new Humanity('韩梅梅','女');
echo $hanMM->name;
$zhaoKuangYing=new Humanity('赵匡胤','男');
echo $zhaoKuangYing->name;
//手动销毁对象
unset($hanMM);