You are viewing documentation for an outdated version. It is no longer supported!
Json
All DTOs inherit from JsonSerializable
. This means that when using json_encode()
, the DTO automatically ensures that its properties are serializable by the encoding method.
Encoding
json_encode()
Via $person = new Person([
'name' => 'Rian Dou',
'age' => 29
]);
echo json_encode($person);
The above example will output the following Json string;
{
"name":"Rian Dou",
"age":29
}
toJson()
Via You can also perform json serialization directly on the DTO, by invoking the toJson()
method.
$person = new Person([
'name' => 'Rian Dou',
'age' => 29
]);
echo $person->toJson(); // The same as invoking json_encode($person);
Populate from Json
To populate a DTO directly from a Json string, use the fromJson()
method.
$json = '{"name":"Miss Mossie Wehner Sr.","age":28}';
$person = Person::fromJson($json);
echo $person->name; // Miss Mossie Wehner Sr.
Note
fromJson()
returns a new DTO instance.