트레이트 구현 재사용
Coddy의 C# 개발자를 위한 PHP 코스 레슨. 48개 중 39번째.
C#의 기본 인터페이스 메서드는 인터페이스 계약을 통해 구현을 제공하지만, 인터페이스는 여전히 하나의 타입입니다. PHP 트레이트는 매개변수 타입으로 사용할 수 없으면서도 구현을 제공합니다. PHP 트레이트와 인터페이스는 별개의 설계 선택지로 유지해야 합니다. 이 C# 호출은 의도적으로 인터페이스 타입의 수신자를 사용합니다.
트레이트는 use를 통해 클래스에 재사용 가능한 메서드를 제공합니다. 트레이트는 인스턴스화할 수 없으며 매개변수에 사용할 인터페이스 타입도 아닙니다. 트레이트는 상속과 별도로 구현 재사용을 해결합니다. 트레이트가 충돌할 때는 include 순서에 의존하지 말고 insteadof로 우선순위를 명시적으로 정하고 as로 별칭을 지정하세요.
C# 프로그램
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
interface IGreeting{string Hello(){return "hello";}}
class Host:IGreeting{}
static void Main() {
IGreeting host=new Host();Console.WriteLine(host.Hello());
}
}소스 출력:
helloPHP 프로그램
Greeting.php
<?php
declare(strict_types=1);
trait Greeting {public function hello():string{return "hello";}}
Host.php
<?php
declare(strict_types=1);
require_once __DIR__."/Greeting.php";class Host {use Greeting;}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/Host.php";echo (new Host())->hello(),"\n";
PHP 출력:
hello챌린지
쉬움입력은 ASCII 문자열입니다. Trimmed trait는 trim을 반환하는 clean(string):string을 제공합니다. Note와 Label은 모두 Trimmed를 사용합니다. 드라이버는 정리된 텍스트를 |로 구분하여 둘 다에서 출력합니다.
제공된 main 스크립트는 표준 입력에서 JSON 값 하나를 읽고, 이름이 지정된 공개 API를 확인한 다음 결과를 출력합니다. 출력하지 말고 모듈 선언을 구현하세요. 런처를 대체하거나 모듈에서 입력을 읽지 마세요. 입력은 명시된 타입과 범위를 충족합니다.
Trimmed.php, Note.php, Label.php를 수정하세요. main.php는 잠긴 진입 파일입니다. 종속성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.
직접 해보기
<?php
declare(strict_types=1);
require_once __DIR__."/Trimmed.php";
require_once __DIR__."/Note.php";
require_once __DIR__."/Label.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 Note())->clean(" z ")==="z" && (new Label())->clean(" y ")==="y","shared trait");
echo (new Note())->clean($input)."|".(new Label())->clean($input),"\n";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러