In OOP, The ability of a new class to be created, from an existing class by extending it, is called inheritance.
the new class is called the derived class or subclass or child class,
the existing class is called the base class or super-class or parent class.
The child class can extend the functionality of the parent class by adding new properties and methods and by overriding existing ones. (The child class reuses all fields and methods of the parent class (common part) and can implement its own(unique part))
Inheritance describes an IS-A relationship. For example,
When we say that a cat is an animal,we mean that the cat is a specialized kind of animal.
Inheritance helps in organizing classes into a hierarchy and enabling these classes to inherit attributes and behavior from classes above in the hierarchy.
In PHP, the keyword extends is used to declare an inherited class.
<?php
class Phone {
public function sendSMS($msg){
return "Sending text: " . $msg;
}
}
class ApplePhone extends Phone {
private $touchID = "Luauutri";
public function sendiMessage($msg) {
return "Sending an iMessage: " . $msg;
}
}
$myPhone = new ApplePhone();
echo $myPhone -> sendSMS("Hello Lautturi.");
echo $myPhone -> sendiMessage("Hi Lautturi.");
?>
the child class ApplePhone inherits the public method sendSMS() from the parent class Phone.
Additionally, it has its own property touchID and method sendiMessage.
Notice: the parent class must be declared before the child class structure.
Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.
The inherited methods can be overridden by redefining the method with the same name and parameter list.
<?php
class Phone {
public function sendSMS($msg){
return "Sending text: " . $msg;
}
}
class ApplePhone extends Phone {
public function sendSMS($msg) {
return "Using apple phone to send text: " . $msg;
}
}
$myPhone = new ApplePhone();
echo $myPhone -> sendSMS("Hello Lautturi.");
?>
The child class has one overridden method named sendSMS, which overrides the default implementation of the sendSMS method.
When an extending class overrides the parents definition of a method, PHP will not call the parent's method.
To call parent's methods, we can use the parent keyword
<?php
class Phone {
public function sendSMS(){
echo "Phone::sendSMS()\n";
}
}
class ApplePhone extends Phone {
// Override parent's definition
public function sendSMS() {
parent::sendSMS(); // call the parent function
echo "ApplePhone::sendSMS()\n";
}
}
$myPhone = new ApplePhone();
$myPhone -> sendSMS();
?>
Outputs
Phone::sendSMS() ApplePhone::sendSMS()