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方法的区别是什么呢?什么时候会隐式调用呢?

阅读 5.6k
4 个回答

参照文档: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函数封装一下而已,只是为了语义化。

这样?

 public function jsonSerialize()
    {
        return $this->toArray();
    }

public function toJson($options = 0)
    {
        return json_encode($this->jsonSerialize(), $options);
    }    

谢邀!

因为我没用过larval,你可以贴出toJson方法和jsonSerialize方法的具体代码么

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题