Detailed explanation of __wakeup() method in PHP

藏色散人
Release: 2023-04-07 06:36:01
Original
17296 people have browsed it

__wakeup(), when executing unserialize(), this function will be called first

If __sleep() is white, then __wakeup() It's just black.

So why?

Because:

In contrast, `unserialize()` will check whether there is a `__wakeup()` method. If it exists, the `__wakeup` method will be called first to prepare the resources needed by the object in advance.

Function:

__wakeup() is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.

Still look at the code:

<?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;); // 这里必须返回一个数值,里边的元素表示返回的属性名称
    }
    /**
     * __wakeup
     */
    public function __wakeup() {
        echo "当在类外部使用unserialize()时会调用这里的__wakeup()方法<br>";
        $this->name = 2;
        $this->sex = &#39;男&#39;;
        // 这里不需要返回数组
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
var_dump(serialize($person));
var_dump(unserialize(serialize($person)));
Copy after login

Running result:

当在类外部使用serialize()时会调用这里的__sleep()方法
string(58) "O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}" 当在类外部使用serialize()时会调用这里的__sleep()方法
当在类外部使用unserialize()时会调用这里的__wakeup()方法
object(Person)#2 (3) { ["sex"]=> string(3) "男" ["name"]=> int(2) ["age"]=> int(25) }
Copy after login

The above is the detailed content of Detailed explanation of __wakeup() method in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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