Function: JsonSerializable::jsonSerialize()
Applicable version: PHP 5 >= 5.4.0, PHP 7
Usage: The JsonSerializable::jsonSerialize() method is used to serialize an object that implements the JsonSerializable interface. This method is automatically called when the object is encoded in JSON format.
Example:
class MyObject implements JsonSerializable { private $data; public function __construct($data) { $this->data = $data; } public function jsonSerialize() { return $this->data; } } $obj = new MyObject(array('foo' => 'bar', 'baz' => 'qux')); echo json_encode($obj);
Output:
{"foo":"bar","baz":"qux"}
In the example above, we define a class called MyObject
and implement the JsonSerializable
interface. This interface has only one method jsonSerialize()
, which returns data that needs to be serialized to JSON.
In jsonSerialize()
method, we simply return $data
property of the object.
We then create an instance of MyObject
and take an associative array as an argument to the constructor.
Finally, we encode the object as a JSON string using json_encode()
function and output it.
The result is a JSON object containing the $data
attribute: {"foo":"bar","baz":"qux"}
.
Note that when the object is encoded as JSON, jsonSerialize()
method is automatically called to provide the data that needs to be serialized. This means you don't need to call the method manually.