標籤:style blog http java color get
serialize()和unserialize()在php手冊上的解釋是:
serialize — Generates a storable representation of a value
serialize — 產生一個可儲存的值的表示
unserialize — Creates a PHP value from a stored representation
unserialize — 從已儲存的表示中建立 PHP 的值
<?php//聲明一個類class dog { var $name; var $age; var $owner; function dog($in_name="unnamed",$in_age="0",$in_owner="unknown") { $this->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 ‘<BR>‘;/*----------------------------------------------------------------------------------------- 在這裡你可以將字串 $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<br>";print ‘<BR>‘;?>