我很困惑JsonSerializable
如何工作。讓我再詳細說一下這個問題。PHP如何使用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();
因此,我們有一個類,它實現了接口。當我們調用count()
函數時,它已經寫入MyThings
類。這很容易理解。
但是,當我們使用JsonSerializable
接口這樣的:
<?php
class Thing implements JsonSerializable {
public function jsonSerialize() {
// do something
}
}
$obj = new Thing();
//call count method on $obj
json_encode($obj);
jsonSerialize()
內Thing
運行與json_encode()
通話。 如果我們調用
$obj->jsonSerialize();
然後有一個叫jsonSerialize()
裏面的類功能,是可以理解的。但是,當我們運行json_encode()
時,這是如何工作的?這是如何構建在PHP?有人可以解釋這裏使用的模式類型嗎?