개요
상속(Inheritance)은 객체 지향 프로그래밍(OOP) 방법론에서 가장 중요한 핵심 원칙 중 하나입니다. 이 원칙을 활용하면 두 클래스 간의 관계를 정의할 수 있으며, PHP는 객체 모델에서 상속을 완벽하게 지원합니다.
PHP에서는 extends 키워드를 사용하여 두 클래스 사이의 상속 관계를 설정합니다.
기본 문법
class B extends A
여기서 A는 부모 클래스(parent class), 즉 기반 클래스(base class)이며, B는 이를 상속받는 자식 클래스(child class) 또는 서브클래스(subclass)라고 부릅니다.
자식 클래스는 부모 클래스의 public 및 protected 메서드를 모두 상속받습니다. 자식 클래스는 상속받은 메서드를 필요에 따라 재정의(오버라이딩)할 수 있으며, 재정의하지 않으면 부모 클래스에 정의된 기능이 그대로 유지됩니다.
주의할 점은 부모 클래스의 정의가 반드시 자식 클래스보다 먼저 나와야 한다는 것입니다. 즉, 스크립트 내에서 A 클래스의 정의가 B 클래스보다 앞에 위치해야 합니다.
기본 구조 예제
<?php
class A{
// A 클래스의 프로퍼티, 상수, 메서드
}
class B extends A{
// public과 protected 메서드가 상속됨
}
?>오토로딩(autoloading)이 활성화되어 있다면, 부모 클래스의 정의는 해당 클래스 스크립트를 로딩하는 과정에서 자동으로 가져옵니다.
상속 동작 확인하기
다음 코드는 자식 클래스가 부모 클래스의 public 및 protected 멤버를 어떻게 상속받는지 보여줍니다.
예제
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n";
}
protected function protectedmethod(){
echo "This is protected method of parent class\n";
}
private function privatemethod(){
echo "This is private method of parent class\n";
}
}
class childclass extends parentclass{
public function childmethod(){
$this->protectedmethod();
//$this->privatemethod(); // 이 줄은 에러를 발생시킴
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>실행 결과
This is public method of parent class This is protected method of parent class PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'
위 결과에서 알 수 있듯이, private로 선언된 메서드는 자식 클래스에서도 접근할 수 없습니다. 상속되는 것은 오직 public과 protected 멤버뿐이라는 점을 반드시 기억해야 합니다.
메서드 오버라이딩(Method Overriding)
부모 클래스로부터 상속받은 메서드를 자식 클래스에서 다시 정의하면, 새로운 정의가 기존 기능을 대체합니다. 이를 메서드 오버라이딩이라고 합니다.
다음 예제에서는 자식 클래스에서 publicmethod를 다시 정의하고 있습니다.
예제
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n";
}
protected function protectedmethod(){
echo "This is protected method of parent class\n";
}
private function privatemethod(){
echo "This is private method of parent class\n";
}
}
class childclass extends parentclass{
public function publicmethod(){
echo "public method of parent class is overridden in child class\n";
}
}
$obj=new childclass();
$obj->publicmethod();
?>실행 결과
public method of parent class is overridden in child class
자식 클래스의 객체에서 publicmethod를 호출하면 부모 클래스의 정의가 아닌, 자식 클래스에서 재정의한 버전이 실행됩니다.
계층적 상속(Hierarchical Inheritance)
PHP는 다중 상속(multiple inheritance)을 지원하지 않습니다. 따라서 하나의 클래스가 두 개 이상의 클래스를 동시에 확장(extends)할 수 없습니다.
대신 PHP는 아래와 같이 여러 단계로 이어지는 계층적 상속을 지원합니다. C 클래스는 B를 통해 A의 기능까지 간접적으로 상속받게 됩니다.
예제
<?php
class A{
function test(){
echo "method in A class";
}
}
class B extends A{
//
}
class C extends B{
//
}
$obj=new C();
$obj->test();
?>실행 결과
method in A class
C 클래스에는 test() 메서드가 정의되어 있지 않지만, B 클래스를 거쳐 A 클래스로부터 상속받았기 때문에 정상적으로 호출할 수 있습니다.
정리
- 상속은 extends 키워드로 구현하며, 부모 클래스의 public·protected 멤버만 상속됩니다.
- private 멤버는 자식 클래스에서 접근할 수 없습니다.
- 자식 클래스에서 메서드를 재정의하면 부모의 기능이 오버라이딩됩니다.
- PHP는 다중 상속을 지원하지 않지만, 연쇄적인 계층 구조의 상속은 가능합니다.