Difference between toJson method and jsonSerialize method?
大家讲道理
大家讲道理 2017-05-16 13:00:38
0
4
723

When I look at the Illuminate\Support\MessageBag class methods, the class looks like this:

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();
}

Please tell me, seniors, what is the difference between the toJson method and the jsonSerialize method? When will it be called implicitly?

大家讲道理
大家讲道理

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

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