(PHP 5 >= 5.4.0, PHP 7)
JsonSerializable::jsonSerialize — ָ����Ҫ�����л��� JSON ������
���л����壨Object�����ܱ� json_encode() ԭ�������л���ֵ��
�˺���û�в�����
�����ܱ� json_encode() ���л������ݣ� ���ֵ�����dz��� resource ����������͡�
Example #1 JsonSerializable::jsonSerialize() ���� returning an array
<?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 ]
Example #2 JsonSerializable::jsonSerialize() ���� ������һ���������� array
<?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" }
Example #3 JsonSerializable::jsonSerialize() ���� ����һ�� integer
<?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
Example #4 JsonSerializable::jsonSerialize() ���� ����һ�� string
<?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!"