在PHP中,unserialize()
函數(shù)用于將序列化的字符串轉(zhuǎn)換回其原始數(shù)據(jù)結(jié)構(gòu)。要處理自定義類,您需要確保自定義類實(shí)現(xiàn)了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()
函數(shù)序列化自定義類的實(shí)例:$customObject = new CustomClass();
$customObject->property1 = "Hello";
$customObject->property2 = "World!";
$serializedData = serialize($customObject);
echo "Serialized data: " . $serializedData . PHP_EOL;
unserialize()
函數(shù)將序列化的字符串轉(zhuǎn)換回自定義類的實(shí)例:$unserializedData = unserialize($serializedData);
echo "Deserialized object property1: " . $unserializedData->property1 . PHP_EOL;
echo "Deserialized object property2: " . $unserializedData->property2 . PHP_EOL;
輸出結(jié)果:
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!
在這個示例中,我們創(chuàng)建了一個名為CustomClass
的自定義類,實(shí)現(xiàn)了Serializable
接口,并定義了serialize()
和unserialize()
方法。然后,我們使用serialize()
函數(shù)序列化了一個CustomClass
實(shí)例,并使用unserialize()
函數(shù)將其轉(zhuǎn)換回原始數(shù)據(jù)結(jié)構(gòu)。