LoginSignup
11
10

More than 5 years have passed since last update.

JsonSerializableを実装してjson_encode()と仲良くなる

Posted at

PHP 5.4で追加された JsonSerializable インターフェイスを実装すると、オブジェクトに対して json_encode() できるようになります。

<?php

class Foo implements JsonSerializable
{
    public function jsonSerialize()
    {
        return array('foo', 'bar', 'baz');
    }
}

var_dump(json_encode(new Foo())); // string(19) "["foo","bar","baz"]"

最近はバックエンドとフロントエンドをJSONでやりとりする場合がありますが、モデルクラスに対して JsonSerializable を実装しておけば、よりシームレスな感覚でモデルオブジェクトをやり取りできますね。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10