PHpullh
학습 라이브러리/PHP/JsonSerializable 구현

PHP · 객체지향

JsonSerializable 구현

객체가 JSON으로 직렬화될 모양을 스스로 제어하는 예제입니다.

객체지향고급JsonSerializablejsonresource

핵심 설명

객체가 JSON으로 직렬화될 모양을 스스로 제어하는 예제입니다.

PHP code

<?php
class UserResource implements JsonSerializable {
    public function __construct(private int $id, private string $name) {}

    public function jsonSerialize(): array {
        return ['id' => $this->id, 'name' => $this->name];
    }
}

echo json_encode(new UserResource(1, 'mida'));

학습 팁

클래스 예제는 생성자, 가시성, 협력 객체의 책임을 함께 보면 실무 감각이 빨리 붙습니다.

주의할 점

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.

자주 묻는 질문

JsonSerializable 구현란 무엇인가요?

객체가 JSON으로 직렬화될 모양을 스스로 제어하는 예제입니다.

JsonSerializable 구현 학습 시 주의할 점은 무엇인가요?

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.