JsonSerializable::jsonSerialize

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

JsonSerializable::jsonSerializeJSON için dizeleştirilecek veriyi belirtmek için

Açıklama

public function JsonSerializable::jsonSerialize(): mixed

Bir nesneyi json_encode() tarafından yerel olarak dizeleştirilebilen bir değer haline getirir.

Bağımsız Değişkenler

Bu işlevin bağımsız değişkeni yoktur.

Dönen Değerler

json_encode() tarafından yerel olarak dizeleştirilebilecek veriyi resource haricinde bir değer olarak döndürür.

Örnekler

Örnek 1 - Bir dizi döndüren JsonSerializable::jsonSerialize() örneği

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

Yukarıdaki örneğin çıktısı:

[
    1,
    2,
    3
]

Örnek 2 - Bir ilişkisel dizi döndüren JsonSerializable::jsonSerialize() örneği

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

Yukarıdaki örneğin çıktısı:

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

Örnek 3 - Bir tamsayı döndüren JsonSerializable::jsonSerialize() örneği

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

Yukarıdaki örneğin çıktısı:

1

Örnek 4 - Bir dize döndüren JsonSerializable::jsonSerialize() örneği

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

Yukarıdaki örneğin çıktısı:

"Hello!"