CKTIS / PHP
JsonSerializable
jsonSerialize levert de waarde voor json_encode.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function jsonSerialize(): mixedjsonSerialize levert de waarde voor json_encode. De methode mag een array of scalair geven en interne toestand weglaten. Geef de gegevens terug, want kant-en-klare JSON-tekst wordt opnieuw als string gecodeerd.
class Reading implements JsonSerializable { public function __construct(private int $n){} public function jsonSerialize(): mixed{return ["n"=>$this->n];} }
class Encoded implements JsonSerializable { public function jsonSerialize(): mixed{return "{\"n\":2}";} }
echo json_encode([new Reading(2),new Encoded()]);
[{"n":2},"{\"n\":2}"]
Voorbeelden
<?php
class Reading implements JsonSerializable { public function __construct(private int $n){} public function jsonSerialize(): mixed{return ["n"=>$this->n];} }
class Encoded implements JsonSerializable { public function jsonSerialize(): mixed{return "{\"n\":2}";} }
echo json_encode([new Reading(2),new Encoded()]);
Resultaat
[{"n":2},"{\"n\":2}"]