익명 클래스
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 58번째.
때로는 완전한 class를 정의하는 번거로움 없이 간단한 일회성 객체가 필요합니다. Anonymous 클래스를 사용하면 필요한 바로 그곳에서 즉석으로 객체를 만들 수 있습니다. 특히 의존성 주입과 함께 사용할 때 유용합니다.
익명 클래스는 new class 뒤에 클래스 본문을 작성하여 정의합니다.
<?php
$logger = new class {
public function log(string $message): void {
echo "Log: $message";
}
};
$logger->log("Hello!");
출력:
Log: Hello!Anonymous class는 interface를 구현할 때 강력합니다. 이는 테스트에 아주 적합하거나, single-use class로 코드베이스를 어지럽히지 않고 빠르게 구현해야 할 때 유용합니다:
<?php
interface Notifier {
public function send(string $message): string;
}
function notify(Notifier $notifier, string $msg): string {
return $notifier->send($msg);
}
$result = notify(new class implements Notifier {
public function send(string $message): string {
return "Sent: $message";
}
}, "Test message");
echo $result;
출력:
Sent: Test messageAnonymous class는 다른 class를 확장하고, 트레이트를 사용하며, constructor 인수를 받을 수도 있습니다. 이들은 OOP 기능에 완전히 접근할 수 있습니다. 단지 별도의 파일이 아니라 인라인으로 정의될 뿐입니다. 완전한 class 정의가 과도하지만 객체 지향 동작은 여전히 필요할 때 사용하세요.
챌린지
쉬움anonymous class의 강력한 기능을 보여 주는 data formatter 시스템을 만들어 보겠습니다. 간단한 일회성 구현을 위해 별도의 class 파일을 만드는 대신, 필요한 곳에서 바로 빠르게 구현을 만들기 위해 anonymous class를 사용합니다.
코드를 두 개의 파일로 구성합니다.
FormatterInterface.php:FormatterInterface라는 interface를 Define하고, 단일 method인format(string $data): string을 정의합니다. 이를 통해 모든 formatter가 따라야 하는 계약을 설정합니다.main.php: interface 파일을 포함하고 dependency injection을 사용하여 모든 formatter를 받을 수 있는DataProcessorclass를 만듭니다. 이 class는 다음을 수행해야 합니다.- constructor에서
FormatterInterface를 받습니다. - 주입된 formatter에 위임하고 그 result를 return하는
process(string $data)method를 have합니다.
두 개의 입력을 받습니다. format type(
"upper"또는"reverse")과 format할 string입니다.format type에 따라
FormatterInterface를 implements하는 anonymous class를 만듭니다."upper"의 경우:format()method는 data를 uppercase로 변환한 값을 return해야 합니다."reverse"의 경우:format()method는 data를 reversed한 값을 return해야 합니다.
anonymous class를
DataProcessor에 주입하고, input string으로process()를 Call한 다음 result를 print합니다.- constructor에서
이 접근 방식은 single-use class 파일로 코드베이스를 복잡하게 만들지 않고 빠른 구현이 필요할 때 적합합니다. anonymous class는 코드 안에서 바로 생성되고, 필요한 interface를 implements하며, 해당 interface가 예상되는 어디에든 전달할 수 있습니다.
직접 해보기
<?php
require_once 'FormatterInterface.php';
// TODO: DataProcessor 클래스를 생성하세요:
// - 생성자에서 FormatterInterface를 받습니다
// - formatter에 위임하는 process(string $data) 메서드를 가집니다
// 입력 읽기
$formatType = trim(fgets(STDIN));
$inputString = trim(fgets(STDIN));
// TODO: Based on $formatType ("upper" or "reverse"), create an anonymous class
// FormatterInterface를 구현하는
// - "upper"의 경우: format()은 데이터의 대문자 버전을 반환해야 합니다
// - "reverse"의 경우: format()은 데이터의 역순 버전을 반환해야 합니다
// TODO: Create a DataProcessor with your anonymous class formatter
// 입력 문자열로 process()를 호출하고 결과를 출력하세요
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러