php serialize()與unserialize()的用法

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

serialize — Generates a storable representation of a value

serialize — 產生一個可儲存的值的表示

unserialize — Creates a PHP value from a stored representation

unserialize — 從已儲存的表示中建立 PHP 的值

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 '
';?>

其實serialize()就是將PHP中的變數如對象(object),數組(array)等等的值序列化為字串後儲存起來.序列化的字串我們可以儲存在其他地方如資料庫、Session、Cookie等,序列化的操作並不會丟失這些值的類型和結構。這樣這些變數的資料就可以在PHP頁面、甚至是不同PHP程式間傳遞了。而unserialize()就是把序列化的字串轉換回PHP的值。當序列化對象時,PHP 將試圖在序列動作之前調用該對象的成員函數 __sleep()。這樣就允許對象在被序列化之前做任何清除操作。類似的,當使用 unserialize() 恢複對象時, 將調用 __wakeup() 成員函數unserialize() 對單一的已序列化的變數進行操作,將其轉換回 PHP 的值。返回的是轉換之後的值,可為 integer、float、string、array 或 object。如果傳遞的字串不可解序列化,則返回 FALSE。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.