我对JsonSerializable工作原理感到困惑.让我详细说明一下这个问题.
通常我们使用这样的接口:
<?php
interface Countable {
/* Methods */
public function count();
}
class MyThings implements Countable
{
public function count() {
return count($this->arrayOfThings);
}
}
$obj = new MyThings();
//call count method on $obj
$obj->count();
Run Code Online (Sandbox Code Playgroud)
所以我们有一个类,它实现了接口.当我们调用count()函数时,它已经在MyThings类中编写了.这很容易理解.
但是当我们使用这样的JsonSerializable界面时:
<?php
class Thing implements JsonSerializable {
public function jsonSerialize() {
// do something
}
}
$obj = new Thing();
//call count method on $obj
json_encode($obj);
Run Code Online (Sandbox Code Playgroud)
jsonSerialize()内部Thing运行与json_encode()呼叫.如果我们打电话,这是可以理解的
$obj->jsonSerialize();
Run Code Online (Sandbox Code Playgroud)
然后jsonSerialize()在类中调用一个函数.但是,当我们跑步时,这是如何工作的json_encode()?这是如何构建在PHP?有人可以解释这里使用的模式类型吗?
然后,使用implement JsonSerializable的对象将实现jsonSerialize()方法。然后,当json_encode()将其输入序列化为JSON时,如果要序列化的值为a JsonSerializable,它将调用该jsonSerialize()方法,并将该方法的结果用作对象的序列化表示形式。
例如,从PHP文档中:
Run Code Online (Sandbox Code Playgroud)<?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
Run Code Online (Sandbox Code Playgroud)
这是json_encode代表数字1 的d值。PHP文档提供了三个以上的示例,它们从对象返回值,但是由于jsonSerialize()允许您指定要返回的实际数据,因此认识到它可以返回任何值很重要。例如:
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);
Run Code Online (Sandbox Code Playgroud)
将输出
{
"boolean": true,
"random_integer": 1140562437,
"int_from_object": 42,
"another_object": {}
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,random_integer它不是存储在任何地方的静态值。它在每次执行时都会改变;并int_from_object演示json_encode()将递归评估JsonSerializable实例。
| 归档时间: |
|
| 查看次数: |
3279 次 |
| 最近记录: |