Php/docs/jsonserializable.jsonserialize

提供:Dev Guides
< Php
移動先:案内検索

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)

JsonSerializable::jsonSerializeJSON にシリアライズしたいデータを指定する


説明

abstract public JsonSerializable::jsonSerialize ( ) : mixed

オブジェクトをシリアライズして、 json_encode() がネイティブにシリアライズできる値にします。


パラメータ

この関数にはパラメータはありません。


返り値

json_encode() でシリアライズするデータを返します。 resource 型以外の任意の型になります。


例1 JsonSerializable::jsonSerialize() で配列を返す例

<?phpclass ArrayValue implements JsonSerializable {    public function __construct(array $array) {        $this->array = $array;    }    public function jsonSerialize() {        return $this->array;    }}$array = [1, 2, 3];echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);?>

上の例の出力は以下となります。


[
    1,
    2,
    3
]

例2 JsonSerializable::jsonSerialize() で連想配列を返す例

<?phpclass ArrayValue implements JsonSerializable {    public function __construct(array $array) {        $this->array = $array;    }    public function jsonSerialize() {        return $this->array;    }}$array = ['foo' => 'bar', 'quux' => 'baz'];echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);?>

上の例の出力は以下となります。


{
    "foo": "bar",
    "quux": "baz"
}

例3 JsonSerializable::jsonSerialize() で整数値を返す例

<?phpclass IntegerValue implements JsonSerializable {    public function __construct($number) {        $this->number = (integer) $number;    }    public function jsonSerialize() {        return $this->number;    }}echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);?>

上の例の出力は以下となります。


1

例4 JsonSerializable::jsonSerialize() で文字列を返す例

<?phpclass StringValue implements JsonSerializable {    public function __construct($string) {        $this->string = (string) $string;    }    public function jsonSerialize() {        return $this->string;    }}echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);?>

上の例の出力は以下となります。


"Hello!"