__serialize和__unserialize魔术方法详解

1.官方文档:

__serialize() and __unserialize() 

public __serialize(): array

public __unserialize(array $data): void

serialize() checks if the class has a function with the magic name __serialize(). If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a TypeError will be thrown.

Note:

If both __serialize() and __sleep() are defined in the same object, only __serialize() will be called. __sleep() will be ignored. If the object implements the Serializable interface, the interface's serialize() method will be ignored and __serialize() used instead.

The intended use of __serialize() is to define a serialization-friendly arbitrary representation of the object. Elements of the array may correspond to properties of the object but that is not required.

Conversely, unserialize() checks for the presence of a function with the magic name __unserialize(). If present, this function will be passed the restored array that was returned from __serialize(). It may then restore the properties of the object from that array as appropriate.

Note:

If both __unserialize() and __wakeup() are defined in the same object, only __unserialize() will be called. __wakeup() will be ignored.

Note:

This feature is available as of PHP 7.4.0.

2.这两个魔术方法需要php7.4以上才能生效

3.当__serialize和__sleep方法同时存在,序列化时忽略__sleep方法而执行__serialize;当__unserialize方法和__wakeup方法同时存在,反序列化时忽略__wakeup方法而执行__unserialize

4.__unserialize的参数:当__serialize方法存在时,参数为__serialize的返回数组;当__serialize方法不存在时,参数为实例对象的所有属性值组合而成的数组

示例:

<?php

class ctfshowvip{
    public $username="877.php";
    public $password="password";
    public $code=0x36d;

    public function __serialize(): array
    {
        return [
            $this->username,
            $this->password
        ];
    }

    public function __unserialize(array $data): void
    {
        print_r($data);
    }

}

$vip=new ctfshowvip();

$vip=unserialize(serialize($vip));

?>

结果:

Array
(
    [0] => 877.php
    [1] => password
)

示例2:

<?php

class ctfshowvip{
    public $username="877.php";
    public $password="password";
    public $code=0x36d;

    /*public function __serialize(): array
    {
        return [
            $this->username,
            $this->password
        ];
    }*/

    public function __unserialize(array $data): void
    {
        print_r($data);
    }

}

$vip=new ctfshowvip();

$vip=unserialize(serialize($vip));

?>

结果:

Array
(
    [username] => 877.php
    [password] => password
    [code] => 877
)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值