Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

JsonSerializable

Define the value that json_encode should serialize for an object.

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

Syntax

public function jsonSerialize(): mixed

Define the value that json_encode should serialize for an object. The method may return an array, scalar or other encodable value and can omit internal state. Return the data itself; returning a pre-encoded JSON string makes the outer encoder produce JSON string contents.

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

Examples

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

Result

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

Sources