상속과 오버라이딩
Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 35번째.
C는 기본 구조체를 포함하고 헬퍼 함수에 위임할 수 있지만, 클래스 상속이나 자동 가상 디스패치는 없습니다. PHP의 extends는 오버라이딩 규칙이 있는 단일 부모 클래스를 제공합니다. 부모 동작을 의도적으로 호출하고 교체 가능한 협력자에는 합성을 사용하세요.
클래스는 최대 하나의 부모 클래스만 확장할 수 있습니다. 오버라이딩하는 메서드는 호환 가능한 가시성과 타입을 준수해야 합니다. parent::method는 부모 구현을 호출하며, 단순히 오버라이딩만 해서는 부모 구현이 호출되지 않습니다. 진정한 대체 가능한 관계에는 상속을, 교체 가능한 협력자에는 합성을 선호하세요. final은 선언된 위치에서 추가 확장이나 오버라이딩을 차단합니다.
C 프로그램
#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
struct Child child = {{3}, 2};
printf("%d\n", child_total(&child, 4));
return 0;
}소스 출력:
14PHP 프로그램
Message.php
<?php
declare(strict_types=1);
class Message {public function text():string{return "base";}}
LoudMessage.php
<?php
declare(strict_types=1);
require_once __DIR__."/Message.php";class LoudMessage extends Message {public function text():string{return strtoupper(parent::text());}}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/LoudMessage.php";echo (new LoudMessage())->text(),"\n";
PHP 출력:
BASE챌린지
쉬움입력은 음이 아닌 정수 점수인 [base,extra]입니다. Score(base)의 points():int는 base를 반환합니다. BonusScore(base,extra)는 Score를 상속받으며, 부모를 초기화하고 extra를 더하도록 points를 오버라이드합니다. base를 독립적으로 사용할 수 있도록 유지하세요.
제공된 메인 스크립트는 표준 입력에서 하나의 JSON 값을 읽고, 지정된 공개 API를 검증하며 결과를 출력합니다. 아무것도 출력하지 않고 모듈 선언을 구현하세요. 실행기를 교체하거나 모듈 내에서 입력을 읽지 마세요. 입력은 명시된 타입과 범위를 충족합니다.
Score.php, BonusScore.php를 수정하세요. main.php는 잠긴 엔트리 파일입니다. 의존성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.
직접 해보기
<?php
declare(strict_types=1);
require_once __DIR__."/Score.php";
require_once __DIR__."/BonusScore.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Score(2))->points()===2,"base");$s=new BonusScore(4,3);ensure($s instanceof Score && $s->points()===7,"override");
echo (string)(new BonusScore(...$input))->points(),"\n";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러