Hàm unserialize

Hàm unserialize nhận một chuỗi đã tuần tự hóa và trả về giá trị PHP tương ứng. Tham số đầu tiên của nó nhận một chuỗi, và tham số thứ hai không bắt buộc - là một mảng tùy chọn để kiểm soát quá trình giải tuần tự hóa.

Cú pháp

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

Ví dụ

Chuyển đổi một chuỗi đã tuần tự hóa trở lại thành mảng:

php<?php
  $serialized = 'a:3:{i:0;s:1:"a";i:1;s:1:"b";i:2;s:1:"c";}';
  $res = unserialize($serialized);
  print_r($res);
?>

Kết quả thực thi mã:

php['a', 'b', 'c']

Ví dụ

Giải tuần tự hóa một đối tượng:

php<?php
  class Test {
    public $prop = 123;
  }
  
  $obj = new Test();
  $serialized = serialize($obj);
  $res = unserialize($serialized);
  
  echo $res->prop;
?>

Kết quả thực thi mã:

php123

Ví dụ

Sử dụng tùy chọn 'allowed_classes':

php<?php
  $serialized = 'O:4:"Test":1:{s:4:"prop";i:123;}';
  $res = unserialize($serialized, ['allowed_classes' => false]);
  var_dump($res);
?>

Kết quả thực thi mã:

phpobject(__PHP_Incomplete_Class)#1 (2) {
  ["__PHP_Incomplete_Class_Name"]=>
  string(4) "Test"
  ["prop"]=>
  int(123)
}

Xem thêm

  • hàm serialize,
    hàm chuyển đổi giá trị thành một chuỗi đã tuần tự hóa
  • hàm json_encode,
    hàm chuyển đổi giá trị thành một chuỗi JSON