From PHP 8.1
It's easy to create DTO object with readonly properties and promoting constructor
which easy to pack into a compact string and covert back to a object.
<?php
function cvtObjectToJson( object $poObject ): string
{
return json_encode( array_values( get_object_vars( $poObject )));
}
function cvtJsonToObject( string $psClass, string $psString ): object
{
return new $psClass( ...json_decode( $psString ));
}
final class exampleDto
{
final public function __construct(
public readonly int $piInt,
public readonly ?int $pnNull,
public readonly float $pfFloat,
public readonly string $psString,
public readonly array $paArray,
public readonly object $poObject,
){}
}
$exampleDtoO = new exampleDto( 1, null, .3, 'string 4', [], new stdClass() );
$stringJson = cvtObjectToJson( $exampleDtoO );$objectO = cvtJsonToObject( exampleDto::class, $stringJson );
echo $exampleDtoO == $objectO
? 'Objects equal, but not identical.'. PHP_EOL
: 'Objects not equal neither identical.'. PHP_EOL
;
var_dump($exampleDtoO, $stringJson, $objectO);