Class Inheritance in OOP in PHP
One class can inherit from another
class, borrowing its methods and properties.
This is needed when two
classes are very similar. For example,
we might have a class User
,
and also a Student
, which
has the same properties and methods,
but also adds its own.
In this case, it would be convenient
for the student to inherit
the repeating methods of the parent.
Let's see how this is done.
Suppose we have a class User
,
which will be the parent:
<?php
class User {
}
?>
Suppose we also have a class for a student, which will be the child:
<?php
class Student {
}
?>
Let's make it so that the child class
inherits the methods and properties of its
parent. This is done using the
keyword extends
:
<?php
class Student extends User {
}
?>
Make a class Employee
,
inheriting from the class User
.