JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)
Specify data which should be serialized to JSON
abstract public mixed JsonSerializable::jsonSerialize ( void )

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

Returns:

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

Examples:
JsonSerializable::jsonSerialize() example returning an array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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:

[
    1,
    2,
    3
]
JsonSerializable::jsonSerialize() example returning an associative array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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:

{
    "foo": "bar",
    "quux": "baz"
}
JsonSerializable::jsonSerialize() example returning an integer
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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:

1
JsonSerializable::jsonSerialize() example returning a string
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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:

"Hello!"
doc_php
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.