Home  >  Article  >  Backend Development  >  PHP custom serialization interface Serializable usage analysis and explanation

PHP custom serialization interface Serializable usage analysis and explanation

jacklove
jackloveOriginal
2018-07-04 17:46:001935browse

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 above example Output:

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

Articles you may be interested in:

How to use PHP’s Opcache acceleration Detailed explanation

How to use Laravel to generate Gravatar avatar address

Detailed discussion of public, private, protected, abstract in PHP Related usage of keywords

The above is the detailed content of PHP custom serialization interface Serializable usage analysis and explanation. 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