<?php
class SomeObject implements JsonSerializable {
public string $placeholder = 'hallo';
public string $id;
public string $model;
public string $value;
public bool $disabled;
public bool $required;
public function jsonSerialize(): mixed
{
return array_map(
fn($value) => $value ?? '',
array_merge(
get_class_vars(__CLASS__),
get_object_vars($this)
)
);
}
}
class MainObject implements JsonSerializable
{
public string $mainName;
public SomeObject $someObject;
public function __construct() {
$this->mainName = (new ReflectionClass(MainObject::class))->getShortName();
$this->someObject = new SomeObject();
}
public function jsonSerialize(): mixed
{
return get_object_vars($this);
}
}
$main = new MainObject;
echo json_encode($main, JSON_PRETTY_PRINT);
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
{
"mainName": "MainObject",
"someObject": {
"placeholder": "hallo",
"id": "",
"model": "",
"value": "",
"disabled": "",
"required": ""
}
}
Output for 7.4.0 - 7.4.33
Fatal error: Uncaught TypeError: Return value of MainObject::jsonSerialize() must be an instance of mixed, array returned in /in/mm8Ss:35
Stack trace:
#0 [internal function]: MainObject->jsonSerialize()
#1 /in/mm8Ss(40): json_encode(Object(MainObject), 128)
#2 {main}
thrown in /in/mm8Ss on line 35
Process exited with code 255.
Output for 7.3.0 - 7.3.33
Parse error: syntax error, unexpected 'string' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /in/mm8Ss on line 4
Process exited with code 255.