Menu
CoddyTech

상속과 오버라이딩

Coddy의 C# 개발자를 위한 PHP 코스 레슨. 48개 중 35번째.

C# 인스턴스 메서드는 기본적으로 비가상이며, 오버라이드하려면 부모 클래스에서 virtual 또는 abstract를, 자식 클래스에서 override를 사용해야 합니다. PHP의 public/protected 메서드는 일반적으로 final이 아닌 한 오버라이드할 수 있습니다. 기본 동작이 동일하다고 가정하지 말고 의도한 디스패치 동작을 구현하세요.

클래스는 부모 클래스를 최대 하나만 상속할 수 있습니다. 오버라이드하는 메서드는 호환되는 가시성과 타입을 따라야 합니다. parent::method는 부모 구현을 호출하며, 단순히 오버라이드한다고 해서 부모 구현이 호출되는 것은 아닙니다. 실제로 대체 가능한 관계에는 상속을 사용하고, 교체 가능한 협력 객체에는 컴포지션을 사용하는 것이 좋습니다. final은 선언된 위치에서 추가 상속 또는 오버라이드를 막습니다.

C# 프로그램

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
class Message{public virtual string Text(){return "base";}}
class LoudMessage:Message{public override string Text(){return base.Text().ToUpperInvariant();}}
 static void Main() {
  Console.WriteLine(new LoudMessage().Text());
 }
}

소스 출력:

BASE

PHP 프로그램

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
challenge icon

챌린지

쉬움

입력은 [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";
quiz icon실력 점검

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

C# 개발자를 위한 PHP의 모든 레슨

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