Menu
Coddy logo textTech

생성자 프로모션 (8.0)

Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 42번째.

PHP 8.0에서는 클래스를 정의할 때 반복적인 코드를 크게 줄여 주는 기능인 생성자 프로퍼티 승격이 도입되었습니다. 프로퍼티를 별도로 선언한 다음 생성자에서 할당하는 대신, 두 작업을 한 단계로 처리할 수 있습니다.

다음은 지금까지 사용해 온 전통적인 접근 방식입니다:

<?php
class Product {
    private string $name;
    private float $price;
    
    public function __construct(string $name, float $price) {
        $this->name = $name;
        $this->price = $price;
    }
    
    public function getInfo(): string {
        return $this->name . ": $" . $this->price;
    }
}

생성자 promotion을 사용하면 생성자 parameters에 접근 제어자를 directly 추가합니다:

<?php
class Product {
    public function __construct(
        private string $name,
        private float $price
    ) {}
    
    public function getInfo(): string {
        return $this->name . ": $" . $this->price;
    }
}

$product = new Product("Laptop", 999.99);
echo $product->getInfo();

출력:

Laptop: $999.99

생성자 매개변수 앞에 private, protected 또는 public을 추가하면 PHP가 자동으로 속성을 생성하고 값을 할당합니다. 동일한 생성자에서 promoted 매개변수와 일반 매개변수를 함께 사용할 수 있으며, 필요한 경우 생성자 본문 안에 로직을 추가할 수도 있습니다.

핵심 요점: 생성자 promotion은 반복적인 속성 선언과 할당을 없애며, 완전한 캡슐화 제어를 유지하면서 클래스를 더 깔끔하고 읽기 쉽게 만듭니다.

challenge icon

챌린지

쉬움

constructor promotion의 우아함을 보여 주는 연락처 관리 시스템을 만들어 보겠습니다. 적절한 캡슐화를 유지하면서 보일러플레이트 코드를 제거하는 깔끔하고 현대적인 PHP class를 만들게 됩니다.

코드를 두 개의 파일로 구성합니다.

  • Contact.php: constructor promotion을 사용하여 constructor signature에서 직접 all properties를 define하는 Contact class를 Create합니다. 연락처에는 다음이 있어야 합니다.
    • private $name property (string)
    • private $email property (string)
    • "Not provided"를 default value로 갖는 private $phone property (string)
    constructor promotion syntax를 사용하세요. 별도의 property declarations는 필요하지 않습니다! "[name] | [email] | [phone]"을 반환하는 public method getFullDetails()를 Add하세요. 또한 "Contact: [name]"을 반환하는 getSummary() method도 Add하세요.
  • main.php: Contact file을 포함합니다. name, email, phone number라는 세 가지 input을 받게 됩니다. 두 개의 Contact instances를 Create하세요.
    • first contact는 세 가지 values (name, email, phone)를 all 사용해야 합니다.
    • second contact는 name과 email만 사용해야 합니다 (default phone value에 의존).
    네 줄을 Print하세요.
    • first contact의 full details
    • first contact의 summary
    • second contact의 full details
    • second contact의 summary

constructor promotion을 사용하면 properties를 define하고, visibility를 설정하고, types를 declare하고, values를 assign하는 작업을 모두 하나의 읽기 쉬운 constructor signature에서 수행할 수 있다는 점에 주목하세요. default value가 있는 optional phone parameter는 promoted parameters가 regular parameters와 마찬가지로 default values와 원활하게 작동한다는 것을 보여 줍니다.

직접 해보기

<?php

require_once 'Contact.php';

// 입력 읽기
$name = trim(fgets(STDIN));
$email = trim(fgets(STDIN));
$phone = trim(fgets(STDIN));

// TODO: 세 값 모두(name, email, phone)로 첫 번째 연락처 생성

// TODO: name과 email만으로 두 번째 연락처 생성 (기본 phone 사용)

// TODO: 첫 번째 연락처의 전체 세부 정보 출력

// TODO: 첫 번째 연락처의 요약 출력

// TODO: 두 번째 연락처의 전체 세부 정보 출력

// TODO: 두 번째 연락처의 요약 출력

?>
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 PHP 컴파일러