共計 634 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 PHP 中,可以使用 serialize() 函數(shù)將對象序列化為字符串,使用 unserialize() 函數(shù)將字符串反序列化為對象。
示例代碼如下:
class Person {public $name;
public $age;
public function __construct($name, $age) {$this->name = $name;
$this->age = $age;
}
}
// 創(chuàng)建一個 Person 對象
$person = new Person('John', 30);
// 將對象序列化為字符串
$serializedPerson = serialize($person);
echo $serializedPerson . "\n";
// 將字符串反序列化為對象
$unserializedPerson = unserialize($serializedPerson);
var_dump($unserializedPerson);
運行上面的代碼,會輸出以下結果:
O:6:"Person":2:{s:4:"name";s:4:"John";s:3:"age";i:30;}
object(Person)#2 (2) {["name"]=>
string(4) "John"
["age"]=>
int(30)
}
可以看到,serialize() 函數(shù)將對象序列化為字符串,字符串中包含了對象的類名和屬性值;unserialize() 函數(shù)將字符串反序列化為對象,并返回一個新的對象。
丸趣 TV 網(wǎng) – 提供最優(yōu)質的資源集合!
正文完