JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0)

JsonSerializable::jsonSerializeSpécifie les données qui doivent être linéarisées en JSON

Description

abstract public mixed JsonSerializable::jsonSerialize ( void )

Linéarise l'objet en une valeur qui peut être linéarisé nativement par la fonction json_encode().

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne les données qui peuvent être linéarisées par la fonction json_encode(), qui peuvent être des valeurs de n'importe quel type autre qu'une ressource.

Exemples

Exemple #1 Exemple avec JsonSerializable::jsonSerialize() retournant un tableau

  1. <?php
  2. class ArrayValue implements JsonSerializable {
  3. public function __construct(array $array) {
  4. $this->array = $array;
  5. }
  6.  
  7. public function jsonSerialize() {
  8. return $this->array;
  9. }
  10. }
  11.  
  12. $array = [1, 2, 3];
  13. echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
  14. ?>
  1. <?php
  2. class ArrayValue implements JsonSerializable {
  3. public function __construct(array $array) {
  4. $this->array = $array;
  5. }
  6.  
  7. public function jsonSerialize() {
  8. return $this->array;
  9. }
  10. }
  11.  
  12. $array = ['foo' => 'bar', 'quux' => 'baz'];
  13. echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
  14. ?>
  1. <?php
  2. class IntegerValue implements JsonSerializable {
  3. public function __construct($number) {
  4. $this->number = (integer) $number;
  5. }
  6.  
  7. public function jsonSerialize() {
  8. return $this->number;
  9. }
  10. }
  11.  
  12. echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
  13. ?>
  1. <?php
  2. class StringValue implements JsonSerializable {
  3. public function __construct($string) {
  4. $this->string = (string) $string;
  5. }
  6.  
  7. public function jsonSerialize() {
  8. return $this->string;
  9. }
  10. }
  11.  
  12. echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
  13. ?>

L'exemple ci-dessus va afficher :

"Hello!"

LoadingChargement en cours