php—Serializable interface

伊谢尔伦
Release: 2023-03-01 09:20:01
Original
1958 people have browsed it

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 )
}
Copy after login

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());
?>
Copy after login

The output of the above routine is similar to:

string(15) "My private data"
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!