Как преобразовать определенные свойства объекта в JSON в PHP - PullRequest
0 голосов
/ 05 июня 2018

У меня есть класс php, скажем:

class StudentDisplay{
private $student_id;
private $student_display;

function getStudent_id() {
    return $this->student_id;
}

function getStudent_display() {
    return $this->student_display;
}

function setStudent_id($student_id) {
    $this->student_id = $student_id;
}

function setStudent_display($student_display) {
    $this->student_display = $student_display;
}

} Но когда я выполняю кодирование json для этого объекта, я хочу, чтобы отображалось только свойство student_id.

Есть ли способя могу легко пойти по этому поводу?

1 Ответ

0 голосов
/ 05 июня 2018

Ваш объект должен реализовать JsonSerializable интерфейс.

class StudentDisplay implements JsonSerializable {

Затем добавить все, что вы хотите, возвращенный в методе jsonSerialize.

public function jsonSerialize()
{
    return [
        'student_id' => $this->student_id,
    ];
}

http://php.net/manual/en/class.jsonserializable.php

...