Computer >> 컴퓨터 >  >> 프로그램 작성 >> PHP

PHP 객체 상속

<시간/>

소개

상속은 객체 지향 프로그래밍 방법론의 중요한 원칙입니다. 이 원리를 이용하여 두 클래스 간의 관계를 정의할 수 있습니다. PHP는 객체 모델에서 상속을 지원합니다.

PHP는 확장을 사용합니다. 두 클래스 간의 관계를 설정하는 키워드입니다.

구문

class B extends A

여기서 A는 기본 클래스(부모라고도 함)이고 B는 하위 클래스 또는 자식 클래스라고 합니다. 자식 클래스는 부모 클래스의 public 및 protected 메서드를 상속합니다. 자식 클래스는 상속된 메서드를 재정의하거나 재정의할 수 있습니다. 그렇지 않은 경우 상속된 메서드는 자식 클래스의 개체와 함께 사용할 때 부모 클래스에 정의된 기능을 유지합니다.

부모 클래스의 정의는 자식 클래스 정의보다 선행되어야 합니다. 이 경우 스크립트에서 A 클래스의 정의가 B 클래스 정의보다 먼저 나와야 합니다.

예시

<?php
class A{
   //properties, constants and methods of class A
}
class B extends A{
   //public and protected methods inherited
}
?>

자동 로딩이 활성화된 경우 클래스 스크립트를 로드하여 상위 클래스의 정의를 얻습니다.

상속 예

다음 코드는 자식 클래스가 부모 클래스의 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(); //this will produce error
   }
}
$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'

메서드 재정의 예

부모 클래스에서 상속된 메서드가 자식 클래스에서 재정의되면 새 정의가 이전 기능을 재정의합니다. 다음 예에서 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

상속적 상속

PHP는 다중 상속을 지원하지 않습니다. 따라서 클래스는 둘 이상의 클래스를 확장할 수 없습니다. 그러나 다음과 같이 계층적 상속을 지원합니다.

예시

<?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