©
本文檔使用 php中文網手册 發布
(mongodb >=1.0.0)
MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
Called during serialization of the object to BSON. The method must return an array or stdClass.
Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\fromPHP() ) will always be serialized as a BSON document. For field values, associative arrays and stdClass instances will be serialized as a BSON document and sequential arrays (i.e. sequential, numeric indexes starting at 0) will be serialized as a BSON array.
此函数没有参数。
An array or stdClass to be serialized as a BSON array or document.
Example #1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document
<?php
class MyDocument implements MongoDB \ BSON \ Serializable
{
function bsonSerialize ()
{
return [ 'foo' => 'bar' ];
}
}
$bson = MongoDB \ BSON \ fromPHP (new MyDocument );
echo MongoDB \ BSON \ toJSON ( $bson ), "\n" ;
?>
以上例程会输出:
{ "foo" : "bar" }
Example #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document
<?php
class MyArray implements MongoDB \ BSON \ Serializable
{
function bsonSerialize ()
{
return [ 1 , 2 , 3 ];
}
}
$bson = MongoDB \ BSON \ fromPHP (new MyArray );
echo MongoDB \ BSON \ toJSON ( $bson ), "\n" ;
?>
以上例程会输出:
{ "0" : 1, "1" : 2, "2" : 3 }
Example #3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field
<?php
class MyDocument implements MongoDB \ BSON \ Serializable
{
function bsonSerialize ()
{
return [ 'foo' => 'bar' ];
}
}
$value = [ 'document' => new MyDocument ];
$bson = MongoDB \ BSON \ fromPHP ( $value );
echo MongoDB \ BSON \ toJSON ( $bson ), "\n" ;
?>
以上例程会输出:
{ "document" : { "foo" : "bar" } }
Example #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field
<?php
class MyArray implements MongoDB \ BSON \ Serializable
{
function bsonSerialize ()
{
return [ 1 , 2 , 3 ];
}
}
$value = [ 'array' => new MyArray ];
$bson = MongoDB \ BSON \ fromPHP ( $value );
echo MongoDB \ BSON \ toJSON ( $bson ), "\n" ;
?>
以上例程会输出:
{ "array" : [ 1, 2, 3 ] }