函数名:MongoDB\Driver\ServerApi::bsonSerialize()
适用版本:MongoDB PHP扩展版本1.9.0及以上
用法:该函数用于将给定的PHP对象序列化为BSON(二进制JSON)格式的文档。
语法:public static function bsonSerialize(object $document): string
参数:
返回值:返回序列化后的BSON字符串。
示例:
<?php
// 示例对象
class User {
public $name;
public $age;
}
$user = new User();
$user->name = "John";
$user->age = 30;
// 序列化对象为BSON
$bson = MongoDB\Driver\ServerApi::bsonSerialize($user);
// 打印序列化后的BSON
var_dump($bson);
?>
输出:
string(34) "{"name":"John","age":30}"
注意事项:
MongoDB\BSON\Serializable接口的自定义类。MongoDB\BSON\fromJSON()函数。