在PHP中,unserialize()
函数用于将序列化的字符串转换回其原始数据结构。要处理自定义类,您需要确保自定义类实现了Serializable
接口,并定义了serialize()
和unserialize()
方法。
以下是一个简单的示例:
Serializable
接口:class CustomClass implements Serializable {
public $property1;
public $property2;
public function serialize() {
// 在这里自定义序列化过程
return serialize([
'property1' => $this->property1,
'property2' => $this->property2,
]);
}
public function unserialize($serializedData) {
// 在这里自定义反序列化过程
$data = unserialize($serializedData);
$this->property1 = $data['property1'];
$this->property2 = $data['property2'];
}
}
serialize()
函数序列化自定义类的实例:$customObject = new CustomClass();
$customObject->property1 = "Hello";
$customObject->property2 = "World!";
$serializedData = serialize($customObject);
echo "Serialized data: " . $serializedData . PHP_EOL;
unserialize()
函数将序列化的字符串转换回自定义类的实例:$unserializedData = unserialize($serializedData);
echo "Deserialized object property1: " . $unserializedData->property1 . PHP_EOL;
echo "Deserialized object property2: " . $unserializedData->property2 . PHP_EOL;
输出结果:
Serialized data: O:7:"CustomClass":2:{s:10:"property1";s:5:"Hello";s:10:"property2";s:5:"World!"}
Deserialized object property1: Hello
Deserialized object property2: World!
在这个示例中,我们创建了一个名为CustomClass
的自定义类,实现了Serializable
接口,并定义了serialize()
和unserialize()
方法。然后,我们使用serialize()
函数序列化了一个CustomClass
实例,并使用unserialize()
函数将其转换回原始数据结构。