Overriding Parent Methods in OOP in PHP
A child class can override a parent method by creating a method with the same name. Let's look at an example. 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;
}
}
?>
Let's create a method with the same name in the child class:
<?php
class Student extends User {
public function setName($name) {
}
}
?>
Typically, overriding parent methods is necessary to change or extend the behavior of that method. In our case, let's add a check for the name length:
<?php
class Student extends User {
public function setName($name) {
if (strlen($name) > 0) {
$this->name = $name;
} else {
echo 'student name error';
}
}
}
?>
Let's make sure that it is the overridden method that is called. First, let's create an object of the child class:
<?php
$student = new Student;
?>
Now let's call our method, passing a valid value to it:
<?php
$student->setName('john');
?>
And now let's call the method, passing an invalid value to it. As a result, we will see the thrown exception:
<?php
$student->setName(''); // error
?>
In the User
class, create
an age getter and setter.
In the Employee
class, override
the age setter and implement a check
that the age is from
18
to 65
years.