MongoDB\BSON\Serializable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Serializable::bsonSerializeProvides an array or document to serialize as BSON

Опис

abstract public array|object MongoDB\BSON\Serializable::bsonSerialize ( void )

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.

Приклади

Приклад #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" }

Приклад #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function 
bsonSerialize()
    {
        return [
123];
    }
}

$bson MongoDB\BSON\fromPHP(new MyArray);
echo 
MongoDB\BSON\toJSON($bson), "\n";

?>

Наведений вище приклад виведе:

{ "0" : 1, "1" : 2, "2" : 3 }

Приклад #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" } }

Приклад #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function 
bsonSerialize()
    {
        return [
123];
    }
}

$value = ['array' => new MyArray];
$bson MongoDB\BSON\fromPHP($value);
echo 
MongoDB\BSON\toJSON($bson), "\n";

?>

Наведений вище приклад виведе:

{ "array" : [ 1, 2, 3 ] }

Прогляньте Також

add a note add a note

User Contributed Notes 1 note

up
-1
Anonymous
8 years ago
This documentation seems to be obsolete because I tried the first example and it doesn't convert the objectId to a string.

This seems to be more current documentation but I can't figure out how to get bson to json

http://mongodb.github.io/mongo-php-library/api/source-class-MongoDB.Model.BSONDocument.html#48-57
To Top