도구
로그인
한국어

코드 배우기PHP

PHP 상속

PHP 8.3 기준

택배 요금 예제로 PHP 상속을 봐요. extends, parent::, 덮어쓰기와 final 을 한 줄씩 따라가요.

한 줄 뜻

상속은 이미 있는 클래스(부모)의 속성과 메서드를 그대로 받고, 다른 부분만 새로 적는 방법이에요. PHP 는 extends 로 부모를 하나만 고를 수 있고, 덮어쓴 메서드 안에서 parent:: 로 부모 것을 불러요.

왜 필요한가

택배 종류마다 클래스를 처음부터 쓰면 받는 곳, 무게, 무게별 요금, 송장 꼴이 클래스 수만큼 복사돼요. 무게 기준이 2000g 에서 2500g 으로 바뀌면 모든 파일을 고쳐야 해요.

공통 규칙은 Parcel 에 한 번만 두고, 빠른 택배는 "+2500원", 깨지기 쉬운 택배는 "두 배"처럼 다른 점만 적어요. 기준이 바뀌면 부모 한 곳만 고치면 돼요.

일상 비유

편의점 택배 접수표를 떠올려 보세요. 기본 접수표에 받는 곳·무게·요금 칸이 있고, 빠른 배송 접수표는 거기에 "도착 시간" 칸 하나를 더 붙였을 뿐이에요. 기본 칸은 그대로 물려받고 다른 칸만 더한 것이 상속이에요.

예제 코드

main.php · 59줄
<?phpdeclare(strict_types=1); class Parcel{    public function __construct(        protected string $to,        protected int $grams,    ) {    }     public function fee(): int    {        $fee = $this->grams > 2000 ? 4500 : 3000;        return $fee;    }     public function label(): string    {        return sprintf('%-6s %5dg %5d won', $this->to, $this->grams, $this->fee());    }} class ExpressParcel extends Parcel{    public function __construct(string $to, int $grams, private string $slot)    {        parent::__construct($to, $grams);    }     public function fee(): int    {        return parent::fee() + 2500;    }     public function label(): string    {        return parent::label() . " ({$this->slot})";    }} final class FragileParcel extends Parcel{    public function fee(): int    {        $fee = parent::fee() * 2;        return $fee;    }} $list = [    new Parcel('Busan', 800),    new ExpressParcel('Seoul', 2400, 'by 9pm'),    new FragileParcel('Jeju', 1200),];foreach ($list as $p) {    echo $p->label(), "\n";}var_dump($list[1] instanceof Parcel, $list[2] instanceof ExpressParcel);

언제 사용하나

  • "빠른 택배는 택배다"처럼 "~는 ~이다"가 자연스럽게 들릴 때
  • 부모의 규칙을 대부분 그대로 사용하고 몇 군데만 바꿀 때
  • 부모를 더 물려주고 싶지 않다면 final class 로 막아요. 실수로 깊은 상속 사슬이 생기는 것을 막아 줘요.

PHP 는 부모를 하나만 가질 수 있어요. 여러 클래스에 같은 메서드를 넣고 싶을 때는 trait(합성과 static 주제), 같은 약속만 맞추고 싶을 때는 interface(다형성 주제)를 사용해요.

자주 하는 실수

자식 생성자에서 parent::__construct() 를 빼먹음

자바와 달리 PHP 는 자식에 생성자가 있으면 부모 생성자를 저절로 부르지 않아요. 부모가 채워야 할 $to 가 빈 채로 남아 읽는 순간 멈춰요. 자식 생성자 첫머리에서 직접 불러요.

틀린 코드

class Parcel{    public function __construct(protected string $to)    {    }} class ExpressParcel extends Parcel{    public function __construct(string $to, private string $slot)    {    }     public function show(): string    {        return "{$this->to} {$this->slot}";    }} echo (new ExpressParcel('Seoul', '9pm'))->show(), "\n";

실행하면Fatal error: Uncaught Error: Typed property Parcel::$to must not be accessed before initialization

고친 코드

class Parcel{    public function __construct(protected string $to)    {    }} class ExpressParcel extends Parcel{    public function __construct(string $to, private string $slot)    {        parent::__construct($to);    }     public function show(): string    {        return "{$this->to} {$this->slot}";    }} echo (new ExpressParcel('Seoul', '9pm'))->show(), "\n";

실행하면Seoul 9pm

덮어쓴 메서드에 꼭 넘겨야 하는 매개변수를 더함

부모 자리에 자식을 넣어도 똑같이 불려야 해서, 덮어쓴 메서드는 부모처럼 fee() 로 부를 수 있어야 해요. 더할 매개변수에는 기본값을 줘요. 이 검사는 실행하기 전, 클래스를 읽을 때 걸려요.

틀린 코드

class Parcel{    public function fee(): int    {        return 3000;    }} class HeavyParcel extends Parcel{    public function fee(int $extra): int    {        return 3000 + $extra;    }}

PHP 가 내는 오류Fatal error: Declaration of HeavyParcel::fee(int $extra): int must be compatible with Parcel::fee(): int

고친 코드

class Parcel{    public function fee(): int    {        return 3000;    }} class HeavyParcel extends Parcel{    public function fee(int $extra = 1500): int    {        return parent::fee() + $extra;    }} echo (new HeavyParcel())->fee(), "\n";

실행하면4500

final 클래스를 물려받으려 함

final 은 "이 클래스는 더 물려주지 않는다"는 표시예요. 고친 코드처럼 안에 품어서(합성) 사용하거나, 갈래가 필요하면 작성자와 상의해 final 을 풀어요.

틀린 코드

final class FragileParcel{} class GlassParcel extends FragileParcel{}

PHP 가 내는 오류Fatal error: Class GlassParcel cannot extend final class FragileParcel

고친 코드

final class FragileParcel{    public function __construct(public readonly string $note = 'handle with care')    {    }} final class GlassParcel{    public function __construct(private FragileParcel $base = new FragileParcel())    {    }     public function note(): string    {        return $this->base->note . ', glass';    }} echo (new GlassParcel())->note(), "\n";

실행하면handle with care, glass

확인 문제

문제 1

ExpressParcel::fee() 안의 parent::fee() 는 무엇을 부를까요?

답과 까닭 보기

답: 3. 부모 클래스 `Parcel` 의 `fee()` 를 불러요 parent:: 는 바로 위 부모 클래스의 메서드를 불러요. 자식에서 덮어썼더라도 부모의 계산을 빌려 사용하고 그 위에 더할 수 있어요. 이때도 $this 는 자식 객체예요.

문제 2

500g 빠른 택배의 fee() 는 얼마일까요?

$p = new ExpressParcel('Ulsan', 500, 'noon');echo $p->fee(), "\n";

답과 까닭 보기

답: 2. 5500 부모 계산에서 2000g 이하라 3000원, 빠른 택배가 2500원을 더해 5500원이에요.

자주 묻는 것

부모 생성자는 저절로 불리나요?

자식에 생성자가 있으면 저절로 불리지 않아요. 자식 생성자 안에서 parent::__construct() 를 직접 불러야 해요.

PHP 클래스는 부모를 여럿 가질 수 있나요?

아니요, extends 는 하나만 돼요. 여러 클래스에 같은 코드를 넣으려면 trait, 같은 약속을 맞추려면 interface 를 사용해요.

final 은 언제 붙이나요?

더 물려줄 생각이 없는 클래스나 덮어쓰면 안 되는 메서드에 붙여요. 실수로 깊은 상속이 생기는 것을 막아 줘요.