CKTIS / PHP
JsonSerializable
jsonSerialize poda vrednost za serializacijo z json_encode.
Različica: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
public function jsonSerialize(): mixedjsonSerialize poda vrednost za serializacijo z json_encode. Metoda lahko vrne polje ali skalar in izpusti notranje stanje. Vrnite podatke, saj se že pripravljeno besedilo JSON znova kodira kot niz.
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}"]
Primeri
<?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()]);
Rezultat
[{"n":2},"{\"n\":2}"]