Serialize and unserialize Object in PHP

Description

The following code shows how to serialize and unserialize Object.

Example


<?php// ww w .  ja  va 2s  .co  m
  class User
  {
    public $name;
    public $id;

    function __construct()
    {
      //give user a unique ID
      $this->id = uniqid();
    }

    function __sleep()
    {
      //do not serialize this->id
      return(array("name"));
    }

    function __wakeup()
    {
      //give user a unique ID
      $this->id = uniqid();
    }
  }

  //create object
  $u = new User;
  $u->name = "Leon";

  //serialize it
  $s = serialize($u);

  //unserialize it
  $u2 = unserialize($s);

  //$u and $u2 have different IDs
  print_r($u);
  print_r($u2);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition