Home >Backend Development >PHP Tutorial >Detailed explanation of __sleep() method in PHP

Detailed explanation of __sleep() method in PHP

藏色散人
藏色散人Original
2019-07-23 14:54:2710354browse

__sleep(), when executing serialize(), this function will be called first

serialize() function will check whether there is a magic method __sleep() in the class. If it exists, this method will be called first, and then the serialization operation will be performed.

This function can be used to clean the object and return an array containing the names of all variables in the object that should be serialized.

If the method returns nothing, NULL is serialized and an E_NOTICE level error is generated.

Note:

__sleep() cannot return the name of the private member of the parent class. Doing so will generate an E_NOTICE level error. The Serializable interface can be used instead.

Function:

__sleep() method is often used to submit uncommitted data, or similar cleaning operations. At the same time, this function is useful if you have some large objects but do not need to save them all.

Please refer to the following code for details:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    /**
     * @return array
     */
    public function __sleep() {
        echo "当在类外部使用serialize()时会调用这里的__sleep()方法<br>";
        $this->name = base64_encode($this->name);
        return array(&#39;name&#39;, &#39;age&#39;); // 这里必须返回一个数值,里边的元素表示返回的属性名称
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
echo serialize($person);
echo &#39;<br/>&#39;;

Code running results:

当在类外部使用serialize()时会调用这里的__sleep()方法
O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}

The above is the detailed content of Detailed explanation of __sleep() method in PHP. 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