Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Look at the example below.
The __construct() and intro() methods in the child class (Bmw) will override the __construct() and intro() methods in the parent class (Car):
<?php
class Car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The Car is {$this->name} and the color is {$this->color}.";
}
}
class Bmw extends Car {
public $size;
public function __construct($name, $color, $size) {
$this->name = $name;
$this->color = $color;
$this->size = $size;
}
public function intro() {
echo "The car is {$this->name}, the color is {$this->color}, and the size is {$this->size} .";
}
}
$bmw = new Bmw("BMW", "Black", "Medium");
$bmw->intro();
#output
"The car is BMW, the color is Black, and the size is Medium."
The final keyword is PHP.
In order to prevent method overriding or class inheritance, use the final keyword.
The example that follows demonstrates how to stop class inheritance:
<?php
final class Car {
# logic
}
# will result in error
class Bmw extends Car {
# logic
}
The following example shows how to prevent method overriding:
<?php
class Car {
final public function intro() {
# logic
}
}
class Bmw extends Car {
#will result in error
public function intro() {
# logic
}
}
Hope this article will help you to know about Inheritance