PHP에서 OOP 상속 시 생성자
상속 시 부모의 생성자를 재정의할 수 있습니다. 예제를 통해 살펴보겠습니다. 다음과 같은 부모 클래스가 있다고 가정해 보겠습니다:
<?php
class User {
private $name;
private $surn;
public function __construct($name, $surn) {
$this->name = $name;
$this->surn = $surn;
}
public function getName() {
return $this->name;
}
public function getSurn() {
return $this->surn;
}
}
?>
부모 클래스를 상속하는 다음과 같은 클래스가 있다고 가정해 보겠습니다:
<?php
class Student extends User {
}
?>
자식 클래스에서 생성자를 확장하여 추가 매개변수를 넣고 싶다고 가정해 보겠습니다:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
}
}
?>
이 경우 첫 번째 줄에서 parent::__construct()를 통해
반드시 부모 생성자를 호출해야 합니다:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
명령어 parent::__construct()는 본질적으로
부모의 생성자입니다. 따라서
필요한 매개변수를 전달해 보겠습니다:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
이제 자식 클래스에서 학년을 자신의 속성에 기록해 보겠습니다:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
$this->year = $year;
}
}
?>
학년에 대한 getter를 만들어 보겠습니다:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
$this->year = $year;
}
public function getYear() {
return $this->year;
}
}
?>
클래스 Employee가 이번 강의의
클래스 User를 상속한다고 가정해 보겠습니다.
클래스 Employee에서 부모 생성자를 재정의하여
나이와 급여에 대한 매개변수를 추가해 보세요.
나이와 급여에 대한 getter를 만드세요.