Home  >  Article  >  Backend Development  >  Usage analysis of PHP custom serialization interface Serializable

Usage analysis of PHP custom serialization interface Serializable

不言
不言Original
2018-06-19 11:10:092016browse

This article mainly introduces the usage of PHP custom serialization interface Serializable, and analyzes the concept, function, definition and usage of Serializable custom serialization interface in the form of examples. Friends in need can refer to it

The example in this article describes the usage of PHP's custom serialization interface Serializable. Share it with everyone for your reference, the details are as follows:

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

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

Example description:

<?php
/**
 * 类自定义序列化相关操作
 *
 * @author 疯狂老司机
 */
class obj implements Serializable {
  private $data;
  private $step = 0;
  /*
   * 构造函数
   */
  public function __construct() {
    $this->data = "这是一段测试文字<br>";
    echo &#39;调用构造函数<br>&#39;;
  }
  public function serialize() {
    return serialize($this->data);
  }
  public function unserialize($data) {
    $this->step++;
    $this->data = unserialize($data);
  }
  /*
   * 析构函数
   */
  public function __destruct() {
    echo &#39;step:&#39;.$this->step.&#39; 调用析构函数<br>&#39;;
  }
  public function getData(){
    return $this->data;
  }
}
$obj = new obj;// 调用obj::__construct
$ser = serialize($obj);// 调用obj::serialize
$newobj = unserialize($ser);// 调用obj::unserialize
echo $newobj->getData();// 调用obj::getData
// 执行结束,调用析构函数,先执行newobj对象的析构函数在执行obj对象的析构函数
?>

The output of the above example:

调用构造函数
这是一段测试文字
step:1 调用析构函数
step:0 调用析构函数

The above is the entire content of this article, I hope it will be helpful to everyone's learning , please pay attention to the PHP Chinese website for more related content!

Related recommendations:

About how PHP implements the definition and reversal function of linked lists

About PHP object-oriented transactions Script mode

#About data transfer in PHP CURL

The above is the detailed content of Usage analysis of PHP custom serialization interface Serializable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn