php对象串行化

php对象存在于计算机内存中,若是想将对象保存下来,就须要把对象串行化。php

串行化就是把整个对象转化为二进制字符串,使用函数serialize()。对象串行化常常用在数据库

  • 对象须要在网络中传输网络

  • 对象须要永久保存,串行化后写入文件或者数据库。函数

       串行化的逆过程是反串行化,就是把对象串行化转化的二进制字符串再转化为对象,使用函数unserialize()。this

<?php 
    /**
     * 声明一个Person类,用来演示对象串行化
     * @author  youthflies
     */
    class Person
    {
        private $name;
        private $age;
        private $email;
             
        //声明构造函数
        function __construct($name="Tom", $age=1, $email="helloworld@123.com")
        {
            $this->name = $name;
            $this->age = $age;
            $this->email = $email;
        }
             
        public function printInfo()
        {
            echo "<br/>" . $this->name . "  " . $this->age . "  " . $this->email . "<br />";
        }
    }
         
    $person1 = new Person("yeetrack", 12, "yeetrack@123.com");
         
    $person1_string = serialize($person1);
    //将串行化后的字符串打印出来
    echo $person1_string;
    //保存到文件中
    file_put_contents("Person.txt", $person1_string);
    //在将串行化产生的字符串反串行化
    $string = file_get_contents("Person.txt");
    $persion2 = unserialize($string);
    $persion2->printInfo();
?>

运行效果以下图:code

相关文章
相关标签/搜索