函式名:MongoDB\BSON\Persistable::bsonSerialize()
適用版本:MongoDB extension 1.0.0 或更高版本
用法:該方法用於將實現了MongoDB\BSON\Persistable介面的物件序列化為BSON文件。
示例:
<?php
class MyDocument implements MongoDB\BSON\Persistable {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function bsonSerialize() {
return [
'name' => $this->name,
'age' => $this->age
];
}
}
$document = new MyDocument('John Doe', 30);
$serialized = $document->bsonSerialize();
var_dump($serialized);
?>
輸出結果:
array(2) {
["name"]=>
string(8) "John Doe"
["age"]=>
int(30)
}
解釋:在上面的示例中,我們定義了一個實現了MongoDB\BSON\Persistable介面的類MyDocument。該類有兩個私有屬性$name和$age,並透過建構函式進行初始化。然後,我們在bsonSerialize()方法中定義了將物件序列化為BSON文件的邏輯,將$name和$age作為鍵值對返回。最後,我們建立了一個MyDocument物件$document,並呼叫其bsonSerialize()方法,將物件序列化為BSON文件。輸出結果是一個包含'name'和'age'鍵的陣列,對應於物件的屬性值。
熱門工具排行榜