Calling an Overridden Method in OOP in PHP
When overriding, the child loses
access to the overridden method
of the parent. However, it is still possible
to access it. This is done
using the keyword parent
,
which refers to the parent
class.
Let's look at an example when we might need access to the parent method. Suppose we have the following parent class:
<?php
class User {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
?>
Suppose we in the child class overrode the parent method:
<?php
class Student extends User {
public function setName($name) {
if (strlen($name) > 0) {
$this->name = $name;
} else {
echo 'student name error';
}
}
}
?>
It can be noticed that in the overridden method, when the condition is met, essentially the code of the parent method is executed. This results in unnecessary code duplication.
We can get rid of it by calling the parent method. Let's do this:
<?php
class Student extends User {
public function setName($name) {
if (strlen($name) > 0) {
parent::setName($name); // parent method
} else {
echo 'student name error';
}
}
}
?>
Given the following code:
<?php
class User {
private $age;
public function setAge($age) {
if ($age >= 0) {
$this->age = $age;
} else {
echo 'need age more 0';
}
}
}
class Employee extends User {
public function setAge($age) {
if ($age <= 120) {
if ($age >= 0) {
$this->age = $age;
} else {
echo 'need age more 0';
}
} else {
echo 'need age less 120';
}
}
}
?>
In the Employee
class, fix
and simplify the age setter by using
the original parent method.