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

PHP 8.1: New in initializers

( 업데이트: )

initializer에서 new 키워드를 사용할 수 있게 되었습니다. 👏👏👏

그게 무엇이냐? 함수의 인수에 기본값을 할당하는 방법을 알고 있습니까? 예를 들어 $title에 대한 빈 문자열은 다음과 같습니다.

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

기본 객체에서 이제 지정할 수 있습니다.

class BlogData
{
    public function __construct(
        ... string $title = '',
        ... State $state = new Draft(),
    ) {}
}Code language: PHP (php)

이 속성은 public readonly 부분을 알아야 이해가 가능합니다.