상속과 재정의
Coddy의 GDScript 개발자를 위한 PHP 코스 레슨. 48개 중 35번째.
GDScript의 확장은 기본 클래스 하나를 상속하며, 재정의된 메서드에서는 super를 호출해 기본 클래스에 처리를 위임할 수 있습니다. PHP의 extends와 parent 호출도 비슷한 역할을 하며, PHP에만 적용되는 가시성 및 시그니처 규칙을 따릅니다. 상속 계층 구조와 관계없이 의존성을 교체해야 한다면 합성을 우선하세요.
클래스는 부모 클래스를 최대 하나만 확장할 수 있습니다. 메서드를 재정의할 때는 호환되는 가시성과 자료형을 지켜야 합니다. parent::method는 부모 클래스의 구현을 호출하며, 단순히 메서드를 재정의하는 것만으로는 부모 클래스의 구현이 호출되지 않습니다. 실제로 대체 가능한 관계에는 상속을, 교체 가능한 협력 객체에는 합성을 우선하세요. 선언된 곳에서 final은 이후의 확장이나 재정의를 막습니다.
GDScript 프로그램
extends SceneTree
class Base:
var price = 5
func total(quantity):
return price * quantity
class Delivery extends Base:
var fee = 2
func total(quantity):
return super.total(quantity) + fee
func _init():
var delivery = Delivery.new()
print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
quit()출력 결과:
17:2PHP 프로그램
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를 확장하고, 부모를 초기화하며, points를 재정의해 extra를 더합니다. base를 독립적으로도 사용할 수 있도록 하세요.
제공된 main 스크립트는 표준 입력에서 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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러