函數(shù)名稱:Serializable::serialize()
適用版本:PHP 5, PHP 7
函數(shù)描述:Serializable::serialize() 方法用于將對象序列化為字符串。
語法:public string Serializable::serialize ( void )
參數(shù):無
返回值:返回一個包含序列化對象的字符串。
示例:
class Person implements Serializable {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function serialize() {
return serialize([
'name' => $this->name,
'age' => $this->age
]);
}
public function unserialize($data) {
$data = unserialize($data);
$this->name = $data['name'];
$this->age = $data['age'];
}
}
$person = new Person('John Doe', 30);
$serialized = $person->serialize();
echo $serialized;
輸出結果:
O:6:"Person":2:{s:4:"name";s:8:"John Doe";s:3:"age";i:30;}
在上面的示例中,我們定義了一個實現(xiàn)了 Serializable 接口的 Person 類。該類具有 serialize()
方法,用于將對象的屬性序列化為一個字符串。在 serialize()
方法中,我們使用 serialize()
函數(shù)將對象屬性以關聯(lián)數(shù)組的形式進行序列化,并返回序列化后的字符串。
然后,我們創(chuàng)建了一個 Person 對象,并調用 serialize()
方法將其序列化為字符串。最后,我們使用 echo
輸出了序列化后的字符串。
注意:為了正確地序列化和反序列化對象,我們還需要實現(xiàn) unserialize()
方法。在該方法中,我們使用 unserialize()
函數(shù)將序列化后的字符串反序列化為關聯(lián)數(shù)組,并將其賦值給對象的屬性。這樣,我們就可以在需要時重新創(chuàng)建對象,并還原其屬性。