JsonSerializable
An interface defining how an object turns into JSON.
Syntax
class Name implements JsonSerializableReturn value
mixedThe `jsonSerialize()` method returns the data to encode.
Examples
Hiding unwanted properties:
<?php
class User implements JsonSerializable
{
public function __construct(private string $name, private string $password) {}
public function jsonSerialize(): array
{
return ['name' => $this->name];
}
}
echo json_encode([new User('Anna', 'secret'), new User('Oleg', 'qwerty')]);Output:
[{"name":"Anna"},{"name":"Oleg"}]Notes
Without the interface json_encode() outputs only public properties, so private data stays out of the response — but so does the data you need.
See also
- json_encode — Converts a value to a JSON string.
- Stringable — The interface of objects that can be turned into a string.
- get_object_vars — Returns the accessible properties of an object as an array.
In the tutorial
- Built-in interfaces — PHP interfaces that teach an object to behave like an array — Countable, IteratorAggregate, ArrayAccess, JsonSerializable and Stringable.