函数名:MongoDB\BSON\Serializable::bsonSerialize()
适用版本:PHP 5 >= 5.6.0, PHP 7, PECL mongodb >= 1.0.0
用法:这个方法是MongoDB\BSON\Serializable接口的方法,用于将对象序列化为BSON文档。
示例代码:
class MyDocument implements MongoDB\BSON\Serializable {
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', 25);
$serialized = $document->bsonSerialize();
var_dump($serialized);
输出结果:
array(2) {
["name"]=>
string(8) "John Doe"
["age"]=>
int(25)
}
解释:在这个示例中,我们创建了一个名为MyDocument
的类,实现了MongoDB\BSON\Serializable
接口并定义了bsonSerialize()
方法。在bsonSerialize()
方法中,我们返回一个包含name
和age
属性的关联数组。然后,我们创建了一个MyDocument
对象并调用bsonSerialize()
方法将其序列化为BSON文档。最后,我们使用var_dump()
函数打印出序列化后的结果。