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

相關文章
相關標籤/搜索