我在看 IlluminateSupportMessageBag
類別方法時,類別是這樣的:
use JsonSerializable;
use Illuminate\Contracts\Support\Jsonable;
....
class MessageBag implements Jsonable, JsonSerializable...
/*
* Convert the object to its JSON representation.
*/
public function toJson ($options = 0) {
return json_encode($this->jsonSerialize(), $options);
}
/*
*Convert the object into something JSON serializable.
*/
public function jsonSerialize() {
return $this->toArray();
}
請教各位前輩,toJson方法和jsonSerialize方法的差別是什麼呢?什麼時候會隱式呼叫呢?
光陰似箭催人老,日月如移越少年。
參考文件:http://php.net/manual/zh/json...
上程式碼:
class j implements JsonSerializable{
public function jsonSerialize(){
return "Hello world!";
}
}
echo json_encode(new j());
JsonSerializable本身專門為json_encode序列化服務(wù)的,而toJson只是laravel的Jsonable的方法。
也就是說,你使用json_encode對這個物件序列化的時候,會去呼叫jsonSerialize方法。
而你的toJson,一般只是將json_encode函數(shù)封裝一下而已,只是為了語意化。
這樣?
public function jsonSerialize()
{
return $this->toArray();
}
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}