MongoDB\BSON\Serializable::bsonSerialize
  (mongodb >=1.0.0)
MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
  
 
  Açıklama
  
  
  
   Root documents (e.g. a
   MongoDB\BSON\Serializable passed to
   MongoDB\BSON\Document::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.
  
  
   Users are encouraged to include an _id property (e.g. a
   MongoDB\BSON\ObjectId initialized in the constructor)
   when returning data for a BSON root document. In the absence of an
   _id property, the extension or server will generate a
   MongoDB\BSON\ObjectId for insert or upsert
   operations, respectively.
  
  
 
  Bağımsız Değişkenler
  Bu işlevin bağımsız değişkeni yoktur.
  
 
 
 
  Örnekler
  
   Örnek 1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document
   
<?php
class MyDocument implements MongoDB\BSON\Serializable
{
    private $id;
    function __construct()
    {
        $this->id = new MongoDB\BSON\ObjectId;
    }
    function bsonSerialize(): array
    {
        return ['_id' => $this->id, 'foo' => 'bar'];
    }
}
echo MongoDB\BSON\Document::fromPHP(new MyDocument)->toRelaxedExtendedJSON(), "\n";
?>
    
   
Yukarıdaki örnek şuna benzer bir çıktı üretir:
{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }
 
   
  
   Örnek 2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document
   
<?php
class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize(): array
    {
        return [1, 2, 3];
    }
}
echo MongoDB\BSON\Document::fromPHP(new MyArray)->toRelaxedExtendedJSON(), "\n";
?>
    
   
Yukarıdaki örneğin çıktısı:
{ "0" : 1, "1" : 2, "2" : 3 }
 
   
  
   Örnek 3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field
   
<?php
class MyDocument implements MongoDB\BSON\Serializable
{
    function bsonSerialize(): array
    {
        return ['foo' => 'bar'];
    }
}
$value = ['document' => new MyDocument];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>
    
   
Yukarıdaki örneğin çıktısı:
{ "document" : { "foo" : "bar" } }
 
   
  
   Örnek 4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field
   
<?php
class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize(): array
    {
        return [1, 2, 3];
    }
}
$value = ['array' => new MyArray];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>
    
   
Yukarıdaki örneğin çıktısı:
{ "array" : [ 1, 2, 3 ] }