JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)

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

Description

abstract public JsonSerializable::jsonSerialize ( void ) : mixed

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

<?php
class ArrayValue implements JsonSerializable {
    public function 
__construct(array $array) {
        
$this->array $array;
    }

    public function 
jsonSerialize() {
        return 
$this->array;
    }
}

$array = [123];
echo 
json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

L'exemple ci-dessus va afficher :

[
    1,
    2,
    3
]

Exemple #2 Exemple avec JsonSerializable::jsonSerialize() retournant un tableau associatif

<?php
class ArrayValue implements JsonSerializable {
    public function 
__construct(array $array) {
        
$this->array $array;
    }

    public function 
jsonSerialize() {
        return 
$this->array;
    }
}

$array = ['foo' => 'bar''quux' => 'baz'];
echo 
json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

L'exemple ci-dessus va afficher :

{
    "foo": "bar",
    "quux": "baz"
}

Exemple #3 Exemple avec JsonSerializable::jsonSerialize() retournant un entier

<?php
class IntegerValue implements JsonSerializable {
    public function 
__construct($number) {
        
$this->number = (integer) $number;
    }

    public function 
jsonSerialize() {
        return 
$this->number;
    }
}

echo 
json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

L'exemple ci-dessus va afficher :

1

Exemple #4 Exemple avec JsonSerializable::jsonSerialize() retournant une chaîne de caractères

<?php
class StringValue implements JsonSerializable {
    public function 
__construct($string) {
        
$this->string = (string) $string;
    }

    public function 
jsonSerialize() {
        return 
$this->string;
    }
}

echo 
json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

L'exemple ci-dessus va afficher :

"Hello!"