php8.0 주요 문법 변화

Jimin·2024년 8월 5일

php 8.0 이후 주요 문법 변화에 대해 설명한다.

Named Params

기존엔 중간 파라미터 값을 사용하지 않기 위해 default나 Null로 처리하던 것들을 Named Params를 이용해 쉽게 처리가 가능해젔다.

Before

function getUser(string $name, string $type = null, string $address)
{

};

getUser('테스트', null, '서울특별시 강남구');

After

function getUser(string $name, string $type = null, string $address)
{

};

getUser(name: '테스트', address: '서울특별시 강남구');

Nullsafe Operator

null인 객체를 참조할 때 방어코드로 작성할 수 있다.

$user = new User();
$user?->name;

Match

swith문을 대신해 더 간략하게 인라인으로 작성이 가능해젔다.

Before

switch ($type) {
    case 'business':
        $result = "기업유저";
        break;
    default :
  	    $result = "일반유저";
        break;
}

After

$result =. match ($type) {
    'business' => "기업유저",
     default => "일반유저",
};

Constructor property promotion

생성자 문법을 좀 더 간략하게 사용이 가능해젔다. 또한 psr-12 생성자 마지막에 ',' 처리가 가능해젔다.

Before

private $handler;
public function __construct(
    Handler $handler
)
{
    parent::__construct();
    $this->handler = $handler;
}

After

public function __construct(
    private readonly $handle,
) {}

Return Type Mixed

문서에만 존재하던 Mixed가 실제로 사용이 가능해젔다.

class A
{
    public function bar(): mixed
}

class B extends A
{
    public function bar(): int
}

Union Types

interface AInterface
{
    public function foo(): string|int
}

class B implements AInterface
{
    public function foo(): string|int
    {
    
    }
}
profile
도전을 좋아하는 개발자

0개의 댓글