PHP Object Serialization

PHPServer Side ProgrammingProgramming

Introduction

A string representation of any object in the form of byte-stream is obtained by serialze() function in PHP. All property variables of object are contained in the string and methods are not saved. This string can be stored in any file.

To retrieve the object from the byte stream, there is unserialize() function. Definition of corresponding class must be available before calling unserialize()function.

Example

First let us serialize an object of following class and store the string in a file.

<?php
class test1{
   private $name;
   function __construct($arg){
      $this->name=$arg;
   }
}
$obj1=new test1("Kiran");
$str=serialize($obj1);
$fd=fopen("obj.txt","w");
fwrite($fd, $str);
fclose($fd);
?>

In current folder, obj.txt is created. To unserialize, following code reconstructs object from the byte stream read from the given file

Example

<?php
class test1{
   private $name;
   function __construct($arg){
      $this->name=$arg;
   }
   function getname(){
      return $this->name;
   }
}
$filename="obj.txt";
$fd=fopen("obj.txt","r");
$str=fread($fd, filesize($filename));
$obj=unserialize($str);
echo "name: ' . $obj->getname();
?>

Output

Above code now returns name following output

name: Kiran
raja
Published on 18-Sep-2020 15:08:42
Advertisements