PHP的serialize()序列化函數_PHP教程

來源:互聯網
上載者:User
serialize()和unserialize()在php手冊上的解釋是:

serialize — Generates a storable representation of a value,產生一個可儲存的值的表示。

unserialize — Creates a PHP value from a stored representation,從已儲存的表示中建立 PHP 的值。

serialize() 返回字串,此字串包含了表示 value 的位元組流,可以儲存於任何地方。這有利於儲存或傳遞 PHP 的值,同時不丟失其類型和結構。

想要將已序列化的字串變回 PHP 的值,可使用 unserialize() 。 serialize() 可處理除了 resource 之外的任何類型。甚至可以 serialize() 那些包含了指向其自身引用的數組。你正 serialize() 的數組/對象中的引用也將被儲存。

當序列化對象時,PHP 將試圖在序列動作之前調用該對象的成員函數 __sleep() 。這樣就允許對象在被序列化之前做任何清除操作。類似的,當使用 unserialize() 恢複對象時, 將調用 __wakeup() 成員函數。

下面我們試一下這個函數的使用方法:

name = $in_name;        $this->age = $in_age;        $this->owner = $in_owner;    }    function getage() {        return ($this->age * 365);    }        function getowner() {        return ($this->owner);    }        function getname() {        return ($this->name);    }}//執行個體化這個類$ourfirstdog = new dog("Rover",12,"Lisa and Graham");//用serialize函數將這個執行個體轉化為一個序列化的字串$dogdisc = serialize($ourfirstdog);print $dogdisc; //$ourfirstdog 已經序列化為字串 O:3:"dog":3:{s:4:"name";s:5:"Rover";s:3:"age";i:12;s:5:"owner";s:15:"Lisa and Graham";}print '
';/* ----------------------------------------------------------------------------------------- 在這裡你可以將字串 $dogdisc 儲存到任何地方如 session,cookie,資料庫,php檔案 -----------------------------------------------------------------------------------------*///我們在此登出這個類unset($ourfirstdog);/* 還原作業 *//* ----------------------------------------------------------------------------------------- 在這裡將字串 $dogdisc 從你儲存的地方讀出來如 session,cookie,資料庫,php檔案 -----------------------------------------------------------------------------------------*///我們在這裡用 unserialize() 還原已經序列化的對象$pet = unserialize($dogdisc); //此時的 $pet 已經是前面的 $ourfirstdog 對象了//獲得年齡和名字屬性$old = $pet->getage();$name = $pet->getname();//這個類此時無需執行個體化可以繼續使用,而且屬性和值都是保持在序列化之前的狀態print "Our first dog is called $name and is $old days old
";print '
';?>

官方的一個程式例子:


http://www.bkjia.com/PHPjc/752373.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752373.htmlTechArticleserialize()和unserialize()在php手冊上的解釋是: serialize — Generates a storable representation of a value,產生一個可儲存的值的表示。 unserialize — Cre...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.