Usage Analysis of PHP Custom Serialization Interface Serializable

  • 2021-08-31 07:26:46
  • OfStack

This article illustrates the use of PHP custom serialization interface Serializable. Share it for your reference, as follows:

PHP Serializable is the interface for custom serialization. Classes that implement this interface no longer support __sleep () and __wakeup (), the serialize method is automatically called when an instance of the class is serialized, and __destruct () is not called or otherwise affected. When an instance of a class is deserialized, the unserialize () method is called and __construct () is not executed. The interface is summarized as follows:


Serializable {
  abstract public string serialize ( void )
  abstract public mixed unserialize ( string $serialized )
}

Example illustration:


<?php
/**
 *  Class customizes serialization related actions 
 *
 * @author  Crazy old driver 
 */
class obj implements Serializable {
  private $data;
  private $step = 0;
  /*
   *  Constructor 
   */
  public function __construct() {
    $this->data = " This is 1 Segment test text <br>";
    echo ' Call the constructor <br>';
  }
  public function serialize() {
    return serialize($this->data);
  }
  public function unserialize($data) {
    $this->step++;
    $this->data = unserialize($data);
  }
  /*
   *  Destructor 
   */
  public function __destruct() {
    echo 'step:'.$this->step.'  Call destructor <br>';
  }
  public function getData(){
    return $this->data;
  }
}
$obj = new obj;//  Call obj::__construct
$ser = serialize($obj);//  Call obj::serialize
$newobj = unserialize($ser);//  Call obj::unserialize
echo $newobj->getData();//  Call obj::getData
//  At the end of execution, call the destructor and execute first newobj The destructor of the object is executing obj Destructor of object 
?>

The above example outputs:


 Call the constructor 
 This is 1 Segment test text 
step:1  Call destructor 
step:0  Call destructor 

More readers interested in PHP can check out the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: