首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Description

代码语言:javascript
复制
abstract public mixed JsonSerializable::jsonSerialize ( void )

Serializes the object to a value that can be serialized natively by json_encode().

Parameters

This function has no parameters.

Return Values

Returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Examples

Example #1 JsonSerializable::jsonSerialize() example returning an array

代码语言:javascript
复制
<?php
class 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);
?>

The above example will output:

代码语言:javascript
复制
[
    1,
    2,
    3
]

Example #2 JsonSerializable::jsonSerialize() example returning an associative array

代码语言:javascript
复制
<?php
class 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);
?>

The above example will output:

代码语言:javascript
复制
{
    "foo": "bar",
    "quux": "baz"
}

Example #3 JsonSerializable::jsonSerialize() example returning an integer

代码语言:javascript
复制
<?php
class 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);
?>

The above example will output:

代码语言:javascript
复制
1

Example #4 JsonSerializable::jsonSerialize() example returning a string

代码语言:javascript
复制
<?php
class 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);
?>

The above example will output:

代码语言:javascript
复制
"Hello!"

← JsonSerializable

代码语言:txt
复制
 © 1997–2017 The PHP Documentation Group

Licensed under the Creative Commons Attribution License v3.0 or later.

扫码关注腾讯云开发者

领取腾讯云代金券