在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()
函數將其轉換回原始數據結構。