Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / PHP

JsonSerializable

jsonSerialize dodá hodnotu pro serializaci pomocí json_encode.

Verze: PHP 8.4; repository runtime, production runtime not attested

Syntaxe

public function jsonSerialize(): mixed

jsonSerialize dodá hodnotu pro serializaci pomocí json_encode. Metoda může vrátit pole či skalár a vynechat vnitřní stav. Vraťte data, protože hotový text JSON se znovu zakóduje jako řetězec.

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}"]

Příklady

<?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()]);

Výsledek

[{"n":2},"{\"n\":2}"]

Zdroje