- array_map: documentation ( source)
- array_merge: documentation ( source)
- get_object_vars: documentation ( source)
- get_class_vars: documentation ( source)
- json_encode: documentation ( source)
<?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);