php - toJson方法和jsonSerialize方法的区别?
大家讲道理
大家讲道理 2017-05-16 13:00:38
0
4
690

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

大家讲道理
大家讲道理

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

reply all(4)
Peter_Zhu

Refer to the document: http://php.net/manual/zh/json...
Upload the code:

class j implements JsonSerializable{
    public function jsonSerialize(){
        return "Hello world!";
    }
}
echo json_encode(new j());

JsonSerializable itself specifically serves json_encode serialization, and toJson is just the Jsonable method of laravel.

In other words, when you use json_encode to serialize this object, the jsonSerialize method will be called.

And your toJson usually just encapsulates the json_encode function, just for semantics.

phpcn_u1582

Like this?

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

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

I don’t know much about it, so I searched it for you:
http://www.cnblogs.com/gniele...

phpcn_u1582

Thanks for the invitation!

Because I have never used larval, can you post the specific code of toJson method and jsonSerialize method

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!