Constructor in Inheritance in OOP in PHP
When inheriting, you can override the parent's constructor. Let's look at an example. Suppose we have the following parent class:
<?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;
}
}
?>
Suppose the following class inherits from the parent class:
<?php
class Student extends User {
}
?>
Suppose we want to extend the constructor in the child class by adding additional parameters to it:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
}
}
?>
In this case, we must
call the parent constructor via
parent::__construct()
on the first line:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
The parent::__construct()
command is essentially
the parent's constructor. Therefore,
let's pass the required parameters into it:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
Now, in the child class, let's record the year of study in the child's own property:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
$this->year = $year;
}
}
?>
Let's make a getter for the year of study:
<?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;
}
}
?>
Let the Employee
class inherit
from the User
class from this
lesson.
Override the parent constructor in the Employee
class, adding parameters for age and salary to it.
Make getters for age and salary.