按照PHP的序列化协议
此方法最大的优势,可以将“对象完整保存”
class Person{
private $age;
public function __construct($age)
{
$this->age=$age;
}
public function sayAge(){
return $this->age;
}
}
$p1=new Person(100);
$s=serialize($p1);
$p2=unserialize($s);
echo $p2->sayAge(),PHP_EOL;
按照json格式
- 此方法不能将方法,私用的属性进行序列化。
- 最佳实践,使用stdClass对象即可,并不需要型别信息。
class Human{
public $name='john';
private $age=100;
public $favs=['bas','swim'];
public $addrs=[];
public function __construct()
{
$a1=new stdClass();
$a1->tel='123';
$a2=new stdClass();
$a2->tel='456';
array_push($this->addrs,$a1);
array_push($this->addrs,$a2);
}
}
$h1=new Human;
//序列化
$rs=json_encode($h1);
echo $rs,PHP_EOL;
//反序列化
$obj=json_decode($rs);//$obj是一个stdClass对象
print_r($obj);
结果如下:
{"name":"john","favs":["bas","swim"],"addrs":[{"tel":"123"},{"tel":"456"}]}
stdClass Object
(
[name] => john
[favs] => Array
(
[0] => bas
[1] => swim
)
[addrs] => Array
(
[0] => stdClass Object
(
[tel] => 123
)
[1] => stdClass Object
(
[tel] => 456
)
)
)