跳转到主要内容

jsonserialize

JsonSerializable::jsonSerialize

Specify data which should be serialized to JSON

ENTITY

public

mixed

JsonSerializable::jsonSerialize

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

ENTITY ENTITY

ENTITY

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

ENTITY

JsonSerializable::jsonSerialize example returning an ENTITY

<?php
class ArrayValue implements JsonSerializable {
    private $array;
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize(): mixed {
        return $this->array;
    }
}

$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

    

ENTITY

[
    1,
    2,
    3
]

JsonSerializable::jsonSerialize example returning an associative ENTITY

<?php
class ArrayValue implements JsonSerializable {
    private $array;
    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);
?>

    

ENTITY

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

JsonSerializable::jsonSerialize example returning an ENTITY

<?php
class IntegerValue implements JsonSerializable {
    private $number;
    public function __construct($number) {
        $this->number = (int) $number;
    }

    public function jsonSerialize() {
        return $this->number;
    }
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

    

ENTITY

1

JsonSerializable::jsonSerialize example returning a ENTITY

<?php
class StringValue implements JsonSerializable {
    private $string;
    public function __construct($string) {
        $this->string = (string) $string;
    }

    public function jsonSerialize() {
        return $this->string;
    }
}

echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

    

ENTITY

"Hello!"