Codectionary / Developer documentation / PHP

Control Object JSON with JsonSerializable

Choose an explicit JSON representation for an object instead of relying on public-property exposure.

What it is and why to use it

An object’s internal state is not always the response shape an API should expose. JsonSerializable gives the class a jsonSerialize() method whose returned value is encoded by json_encode(). This lets the class describe a deliberate transport representation, such as a public lesson title and duration, rather than exposing incidental implementation details.

How it works

Implement JsonSerializable and return a JSON-encodable value from jsonSerialize(). Returning an associative array produces an object shape for these string keys; returning a sequential array produces a list. Return data, not a string that has already been JSON encoded, or it will be encoded as a JSON string. JSON_THROW_ON_ERROR makes encoding failures explicit. The mixed return type used here is available in PHP 8.0.

Common mistakes and limitations

A private property is not automatically secret if your jsonSerialize implementation returns it. Choose fields explicitly and apply authorisation before returning responses. Avoid recursion and unsupported values such as resources. Valid JSON does not make its strings safe to insert directly into an HTML document.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

class Lesson implements JsonSerializable { public function jsonSerialize(): mixed { return ['title' => 'PHP']; } }

Examples

Expose only selected lesson fields

Keep a local administrative note out of the public representation.

<?php
declare(strict_types=1);

class Lesson implements JsonSerializable {
    public function __construct(private string $title, private string $internalNote) {}
    public function jsonSerialize(): mixed {
        return ['title' => $this->title];
    }
}
$lesson = new Lesson('PHP arrays', 'Check draft before publication');
echo json_encode($lesson, JSON_THROW_ON_ERROR), PHP_EOL;
  1. Both properties are private, but jsonSerialize deliberately selects only title.
  2. json_encode detects the interface and encodes the returned associative array.
  3. The note is absent because the method omitted it, not because the interface automatically filters sensitive information. A real endpoint still checks whether the caller may see the lesson.
  4. Expected output: {"title":"PHP arrays"}

Return computed data rather than pre-encoded JSON

Create a stable summary shape from private progress values.

<?php
declare(strict_types=1);

class Progress implements JsonSerializable {
    public function __construct(private int $completed, private int $total) {}
    public function jsonSerialize(): mixed {
        return [
            'completed' => $this->completed,
            'remaining' => max(0, $this->total - $this->completed),
        ];
    }
}
echo json_encode(new Progress(3, 5), JSON_THROW_ON_ERROR), PHP_EOL;
  1. The method calculates remaining from the internal values instead of storing a second mutable counter.
  2. It returns a PHP array; json_encode performs the actual JSON encoding once.
  3. The result contains numbers, not numeric strings. Production constructors should enforce the allowed ranges for completed and total.
  4. Expected output: {"completed":3,"remaining":2}

Best practices

  • Return an explicit data representation instead of all object fields.
  • Handle encoding failures and keep transport data separate from HTML escaping.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading