Menu
Coddy logo textTech

기본 상속

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

상속을 사용하면 한 class가 다른 class에서 property와 method를 물려받을 수 있습니다. 동일한 코드를 다시 작성하는 대신, 공통 기능을 포함하는 기본 class를 만들고 다른 class가 이를 상속하도록 할 수 있습니다.

상속되는 parent class(또는 기본 class)를 parent class라고 하며, 상속하는 class를 자식 class라고 합니다. 이 관계를 설정하려면 extends 키워드를 사용합니다:

<?php
class Animal {
    public $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    public function speak() {
        return "$this->name makes a sound";
    }
}

class Dog extends Animal {
    public function fetch() {
        return "$this->name fetches the ball";
    }
}

$dog = new Dog("Buddy");
echo $dog->speak() . "\n";
echo $dog->fetch();

출력:

Buddy makes a sound
Buddy fetches the ball

Dog 클래스는 Animal$name 프로퍼티, 생성자 및 speak() 메서드에 자동으로 액세스할 수 있습니다. 또한 개만 가지는 자체 fetch() 메서드를 정의합니다.

이는 명확한 계층 구조를 만듭니다. 모든 dog는 동물이므로 DogAnimal에서 상속받는 것이 합리적입니다. 자식 class는 parent의 모든 것을 사용하면서 고유한 특수 동작을 추가할 수 있습니다.

핵심 사항: 상속은 코드 재사용을 촉진하고 class 간의 논리적 관계를 설정합니다. 자식 class는 parent에서 모든 public 및 보호된 멤버를 상속하므로 중복이 줄어들고 코드를 더 쉽게 유지 관리할 수 있습니다.

challenge icon

챌린지

쉬움

상속을 통해 child class가 parent class의 기능을 공유하면서 자체적인 특수 동작을 추가할 수 있음을 보여 주는 vehicle hierarchy system을 만들어 보겠습니다.

코드를 세 개의 파일로 구성합니다:

  • Vehicle.php: 모든 vehicle의 parent 역할을 하는 Vehicle class를 Define합니다. public $brand property와 brand를 accepts하고 sets하는 constructor가 있어야 합니다. start() method는 "[brand] is starting"을 returns하고, stop() method는 "[brand] is stopping"을 returns하도록 Include합니다.
  • Motorcycle.php: Vehicle을 extends하는 Motorcycle class를 Define합니다. 상단에서 Vehicle 파일을 Include합니다. Motorcycle class는 parent의 constructor를 inherits하므로 자체 constructor가 필요하지 않습니다. wheelie() method를 Add하여 "[brand] is doing a wheelie!"을 returns하도록 합니다. 이는 motorcycle에 고유한 동작입니다.
  • main.php: Motorcycle 파일을 Include합니다(이 파일은 이미 Vehicle을 Include합니다). 하나의 input, 즉 motorcycle brand를 받습니다. 이 brand로 Motorcycle object를 Create합니다. start()를 호출한 result, 그다음 wheelie(), 그다음 stop()을 각각 별도의 줄에 Print합니다.

Motorcycle class가 Vehicle로부터 $brand property, constructor, 그리고 start()stop() method를 자동으로 inherits한다는 점에 주목하세요. child class는 이 경우 wheelie를 할 수 있는 능력처럼 자신을 고유하게 makes하는 요소만 Define하면 됩니다. 이것이 inheritance의 power입니다. 공통 기능은 parent에서 한 번만 작성하고, child가 이를 재사용하면서 자신만의 특수 기능을 Add하도록 합니다.

직접 해보기

<?php
// Motorcycle 클래스를 포함합니다 (이미 Vehicle을 포함함)
require_once 'Motorcycle.php';

// 입력을 읽습니다
$brand = trim(fgets(STDIN));

// TODO: brand로 Motorcycle 객체를 생성합니다

// TODO: start()의 결과를 출력합니다

// TODO: wheelie()의 결과를 출력합니다

// TODO: stop()의 결과를 출력합니다
?>
quiz icon실력 점검

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

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

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