我对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() …
php ×1