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);