3.클래스상속
클래스를상속하려면?
기존에이미작성된클래스를상속(class inheritance)받으면이미작성된메쏘드와멤버변수를그대로이어받게됩니다.
상속받은특성에덧붙여새로운특성을추가하는방법으로새로운클래스를정의하게됩니다.
이와같이기존의클래스로부터특성을이어받는것을상속이라고합니다.
이때확장된클래스를정의하기위해"extends"라는키워드를사용합니다.
부모클래스&자식클래스에관련된용어
기존의클래스와확장된클래스를나타내는용어는객체지향언어마다다양하게사용되고있습니다.
그러나어떤용어를사용하더라도같은의미로사용되고있다고이해하시면됩니다.
기존의클래스확장된클래스
용어영문용어영문
기반클래스baseclass
파생클래스 derived class
수퍼클래스superclass
서브클래스subclass
부모클래스 parent class {}
자식클래스 child class
클래스상속예제
classCart{
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item ($artnr, $num){
$this->items[$artnr]+= $num;
}
// Take $num articles of $artnr out of the cart
function remove_item ($artnr, $num){
if($this->items[$artnr]> $num){
$this->items[$artnr]-= $num;
returntrue;
}else{
returnfalse;
}
}
}
class Named_Cart extendsCart{
var $owner;
function set_owner ($name){
$this->owner = $name;
}
}
클래스 Named_Cart는클래스Cart의모든변수와함수를그대로상속받게되며,새로운멤버인변수 $owner과함수 set_owner()를추가하여정의합니다.
앞서배운new연산자를이용하여클래스 Named_Cart의객체를생성한후장바구니주인을지정하거나주인이누구인지확인할수있습니다.
아울러부모클래스Cart에있는장바구니관련함수를그대로사용할수있습니다.
$ncart =new Named_Cart; // Create a named cart
$ncart->set_owner ("kris");// Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item ("10",1);// (inherited functionality from cart)
단일상속
PHP는다중상속(multiple inheritance)를지원하지않으며,오로지단일상속만지원합니다.
'WEBD > PHP' 카테고리의 다른 글
Class 사용법 정리 5.범위연산자 (0) | 2020.10.02 |
---|---|
Class 사용법 정리 4. 생성자 (0) | 2020.10.02 |
Class 사용법 정리 2. 객체생성 (0) | 2020.10.02 |
Class 사용법 정리 1. 클래스 정의 (0) | 2020.10.02 |
php에서 mysql 버젼 확인 하기 (0) | 2020.10.02 |