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
)