I know this works:
<?php
class MyDTO
{
public $foo;
public $bar;
}
$dto = new MyDTO();
$dto->foo = 42;
$dto->bar = false;
echo json_encode($dto); // {"foo": 42, "bar": false}
But I cannot find any references to such json_encode()
behavior in the PHP docs. So my question: is it ok to rely on it?
Alternatively, I can implement \JsonSerializable
interface, but I don't like to repeat DTO fields inside \JsonSerializable#jsonSerialize()
considering those DTOs will contain only public fields.
My Answer:
php
class Person {
public $name = "John";
public $age = 30;
}
$person = new Person();
echo json_encode($person);
This will output:
json
{"name":"John","age":30}
Rate this post
5 of 5 based on 6152 votesComments