상현에 하루하루
개발자의 하루

PHP 8.1: Readonly Properties

( 업데이트: )

PHP 8.0에서는 promoted properties속성이 도입 되었습니다 그리고 이제 readonly properties를 얻었습니다! Awesome!

읽기 전용 속성이 무엇인가? 값을 한 번만 설정하도록 허용하고 그 시점부터 속성 값에 대한 변경을 금지하는 속성입니다.

읽기 전용 속성을 사용하는 것은 값 객체와 데이터 전송 개체를 모델링하는 좋은 방법입니다

차이점

PHP 7.4 이전의 DTO는 다음과 같습니다.

class BlogData
{
    /** @var string */
    private $title;

    /** @var State */
    private $state;

    public function __construct (
        string $title,
        State $state
    ) {
        $this->title = $title;
        $this->state = $state;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function getState(): State
    {
        return $this->state;
    }
}Code language: PHP (php)

PHP 7.4에 유형 속성이 추가되어 문서 블록을 버릴 수 있습니다.

class BlogData
{
    private string $title;

    private State $state;

    public function __construct(
        string $title,
        State $state
    ) {
        $this->title = $title;
        $this->state = $state;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function getState(): State
    {
        return $this->state;
    }
}Code language: PHP (php)

다음, PHP8.0에서는 생성자 속성 승격이 추가되어 코드를 더욱 단축할 수 있었습니다.

class BlogData
{
    public function__construct(
        private string $title,
        private State $state,
    ) {}

    public function getTitle(): string
    {
        return $this->title;
    }

    public function getState(): State
    {
        return $this->state;
    }
}Code language: PHP (php)

이제 마지막으로 가장 중요한 영향을 미치는 읽기 전용 속성도 있습니다.

class BlogData
{
    public function __construct(
        public readonly string $title,
        public readonly State $state,
    ) {}
}Code language: PHP (php)