Home  >  Article  >  Backend Development  >  php—Serializable interface

php—Serializable interface

伊谢尔伦
伊谢尔伦Original
2017-03-18 11:35:411914browse

Customized serialization interface.

Classes implementing this interface will no longer support __sleep() and __wakeup(). Whenever an instance needs to be serialized, the serialize method will be called. It will not call __destruct() or have other effects unless this method is called programmatically. When data is deserialized, the class will be aware and call the appropriate unserialize() method instead of calling __construct(). If you need to execute the standard constructor, you should handle it in this method.

Interface Summary

Serializable {
    /* 方法 */
    abstract public string serialize ( void )
    abstract public mixed unserialize ( string $serialized )
}

Example #1 Usage Example

<?php
    class obj implements Serializable {
        private $data;
        public function __construct() {
            $this->data = "My private data";
        }
        public function serialize() {
            return serialize($this->data);
        }
        public function unserialize($data) {
            $this->data = unserialize($data);
        }
        public function getData() {
            return $this->data;
        }
    }
    $obj = new obj;
    $ser = serialize($obj);
    $newobj = unserialize($ser);
    var_dump($newobj->getData());
?>

The output of the above routine is similar to:

string(15) "My private data"

Method List

Serializable::serialize — String representation of the object

Serializable::unserialize — Construct Object

Related articles:

Sample code of the difference between Serializable and Externalizable in Java serialization

Java serialization of Serializable

java Serialization object serializable Examples of reading and writing data

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