상속과 재정의
Coddy의 Luau 개발자를 위한 PHP 코스 레슨. 48개 중 35번째.
Luau 메타테이블의 __index 체인은 프로토타입과 유사한 대체 동작을 제공할 수 있지만, 내장된 클래스 상속 문법은 없습니다. PHP의 extends는 재정의 및 가시성 규칙을 적용하는 단일 부모 클래스를 지정합니다. 메타테이블을 동일한 클래스로 취급하지 말고 조회와 위임을 의도적으로 변환하세요.
클래스는 최대 하나의 부모 클래스를 상속합니다. 재정의하는 메서드는 호환되는 가시성 및 타입을 따라야 합니다. parent::method는 부모 구현을 호출하며, 단순히 재정의하는 것만으로는 부모 구현이 호출되지 않습니다. 실제로 대체 가능한 관계에는 상속을, 교체할 수 있는 협력 객체에는 컴포지션을 우선하세요. final은 선언된 곳에서 추가 상속이나 재정의를 막습니다.
Luau 프로그램
local Base={name=function()return "base" end};local Child=setmetatable({name=function()return "child" end},{__index=Base});print(Child.name())
소스 출력:
childPHP 프로그램
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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Luau 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러