How can the JsonSerializable interface be used to serialize objects in PHP?
To serialize objects in PHP, you can use the JsonSerializable interface. By implementing this interface in your class, you can define a method that returns data to be serialized in JSON format when using json_encode(). This allows you to customize how your objects are serialized without needing to modify the json_encode() function itself.
class MyClass implements JsonSerializable {
private $data;
public function __construct($data) {
$this->data = $data;
}
public function jsonSerialize() {
return [
'data' => $this->data
];
}
}
$obj = new MyClass('Hello World');
echo json_encode($obj);
Keywords
Related Questions
- How can PHP developers efficiently append values to existing arrays in a recursive function?
- How can one design a relational database structure in PHP to efficiently store survey participation data for multiple surveys without creating multiple columns for each survey?
- What are the benefits of using printf() over echo for generating HTML output in PHP?