• PHP Video Tutorials

PHP - JsonSerializable::jsonSerialize() Function



JsonSerializable::jsonSerialize() can specify data which can be serialized to JSON.

Syntax

abstract public mixed JsonSerializable::jsonSerialize( void )

JsonSerializable::jsonSerialize() can serialize an object to a value that can be serialized natively by the json_encode() function, and doesn't have any parameters.

JsonSerializable::jsonSerialize() can return data that can be serialized by the json_encode() function, which is the value of any type other than a resource.

Example

<?php
   class ArrayValue implements JsonSerializable {
      public function __construct(array $array) {
         $this->array = $array;
      }
      public function jsonSerialize() {
         return $this->array;
      }
   }
   $array = [1, 2, 3];
   echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

Output

[
    1,
    2,
    3
]
php_function_reference.htm
Advertisements