다음 코드에서 발생할 수 있는 문제는?
다음 코드에서 발생할 수 있는 문제는?
<?php
interface Readable {
public function read();
}
interface Writable {
public function write($data);
}
class File implements Readable, Writable {
public function read() {
return "File content";
}
// write 메서드가 누락됨
}
$file = new File();
echo $file->read();
?>
정답: C
클래스가 인터페이스를 구현할 때는 해당 인터페이스의 모든 메서드를 반드시 구현해야 합니다.
오류 발생 이유:
⦁ 누락된 메서드:
Writable
인터페이스의 write($data)
메서드 미구현⦁ 완전 구현 의무: 인터페이스의 모든 메서드를 구현해야 함
⦁ 컴파일 시점 검사: PHP가 클래스 로딩 시점에 구현 여부를 확인
⦁ Fatal Error: "Class File contains 1 abstract method and must therefore be declared abstract or implement the remaining methods"
다중 인터페이스 구현:
⦁ PHP는 하나의 클래스가 여러 인터페이스를 구현하는 것을 지원
⦁ 문법:
class File implements Readable, Writable
⦁ 모든 인터페이스의 모든 메서드를 구현해야 함
올바른 구현:
class File implements Readable, Writable {
public function read() {
return "File content";
}
public function write($data) {
echo "Writing: " . $data;
}
}
💡 학습 팁
이 문제를 포함한 PHP 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.