php - toJson方法和jsonSerialize方法的区别?
本文介绍了php - toJson方法和jsonSerialize方法的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我在看 Illuminate\Support\MessageBag
类方法时,类是这样的:
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序列化服务的,而toJson只是laravel的Jsonable的方法。
也就是说,你使用json_encode对这个对象序列化的时候,会去调用jsonSerialize方法。
而你的toJson,一般只是将json_encode函数封装一下而已,只是为了语义化。
这篇关于php - toJson方法和jsonSerialize方法的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文