PHP - unserialize() 函式



定義和用法

unserialize() 函式將序列化後的資料轉換回正常的 PHP 值。

語法

mixed unserialize ( string $data , array $options = [] )

引數

序號 引數 描述
1

data

必填。指定序列化後的字串。

2

options

可選。作為關聯陣列提供給 unserialize() 的任何選項。可以是可接受的類名陣列,**false** 表示不接受任何類,或者 **true** 表示接受所有類。**true** 為預設值。

返回值

此函式返回轉換後的值,可以是 bool、int、float、string、array 或 object。如果傳遞的字串不可反序列化,則返回 **false** 併發出 E_NOTICE。

依賴關係

PHP 4 及更高版本。

示例

以下示例演示了首先序列化然後反序列化資料

<?php
  class test1{
     private $name;
     function __construct($arg){
        $this->name=$arg;
     }
     function getname(){
        return $this->name;
     }
  }
  $obj1=new test1("tutorialspoint");
  $str=serialize($obj1); //first serialize the object and save to a file test,txt
  $fd=fopen("test.txt","w");
  fwrite($fd, $str);
  fclose($fd);

  $filename="test.txt";
  $fd=fopen("test.txt","r");
  $str=fread($fd, filesize($filename));
  $obj=unserialize($str);
  echo "name: ". $obj->getname();
?>

輸出

這將產生以下結果:

name: tutorialspoint
廣告