对象implement
Json可序列化 https://www.php.net/manual/en/class.jsonserializable.php然后实施一个json序列化() https://www.php.net/manual/en/jsonserializable.jsonserialize.php方法。那么,当json_encode() https://www.php.net/manual/en/function.json-encode.php正在将其输入序列化为 JSON,如果它正在序列化的值是JsonSerializable
,它调用jsonSerialize()
方法,以及result该方法的 被用作对象的序列化表示。
例如,来自 PHP 文档:
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
将输出
1
哪一个是json_encode
d 值代表数字 1。PHP 文档给出了另外三个这样的例子,从对象返回值,但是因为jsonSerialize()
允许您指定要返回的实际数据,重要的是要意识到它可以返回anything。例如:
class JsonSerializeExample implements JsonSerializable {
public function jsonSerialize() {
return [
'boolean' => true,
'random_integer' => rand(),
'int_from_object' => new IntegerValue(42),
'another_object' => new stdClass,
];
}
}
$obj = new JsonSerializeExample();
echo json_encode($obj, JSON_PRETTY_PRINT);
会输出
{
"boolean": true,
"random_integer": 1140562437,
"int_from_object": 42,
"another_object": {}
}
值得注意的是random_integer
不是存储在任何地方的静态值;它在每次执行时都会改变;和int_from_object
表明json_encode()
将递归地评估JsonSerializable
实例。