亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

php - toJson方法和jsonSerialize方法的差別?
大家講道理
大家講道理 2017-05-16 13:00:38
0
4
847

我在看 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方法的差別是什麼呢?什麼時候會隱式呼叫呢?

大家講道理
大家講道理

光陰似箭催人老,日月如移越少年。

全部回覆(4)
Peter_Zhu

參考文件: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ù)封裝一下而已,只是為了語意化。

phpcn_u1582

這樣?

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

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

我不太了解,幫你搜了個:
http://www.cnblogs.com/gniele...

phpcn_u1582

謝邀!

因為我沒用過larval,你可以貼出toJson方法和jsonSerialize方法的具體代碼麼

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板