JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

JsonSerializable::jsonSerialize指定需要被序列化成 JSON 的数据

说明

public JsonSerializable::jsonSerialize(): mixed

序列化物体(Object)成能被 json_encode() 原生地序列化的值。

参数

此函数没有参数。

返回值

返回能被 json_encode() 序列化的数据, 这个值可以是除了 资源(resource) 外的任意类型。

范例

示例 #1 返回 arrayJsonSerializable::jsonSerialize() 例子

<?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);
?>

以上例程会输出:

[
    1,
    2,
    3
]

示例 #2 返回关联 arrayJsonSerializable::jsonSerialize() 例子

<?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);
?>

以上例程会输出:

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

示例 #3 返回 intJsonSerializable::jsonSerialize() 例子s

<?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);
?>

以上例程会输出:

1

示例 #4 返回 stringJsonSerializable::jsonSerialize() 例子

<?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);
?>

以上例程会输出:

"Hello!"

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top