Abstract Classes In PHP
Abstract Classes:
- An abstract class is a class that contains at least one abstract method. The abstract method is a function declaration without anybody and it has the only name of the method and its parameters.
- There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method
Example of Abstract class
<?php
abstract class Cars {
public abstract function getCompanyName();
public abstract function getPrice();
}
class Baleno extends Cars {
public function getCompanyName() {
return "Maruti Suzuki" . "<br/>";
}
public function getPrice() {
return 720000 . "*<br/>";
}
}
class Santro extends Cars {
public function getCompanyName() {
return "Hyundai" . "<br/>";
}
public function getPrice() {
return 300000 . "*<br/>";
}
}
$car = new Baleno();
$car1 = new Santro();
echo $car->getCompanyName();
echo $car->getPrice();
echo $car1->getCompanyName();
echo $car1->getPrice();
?>
Output
Maruti Suzuki
720000*
Hyundai
300000*
Note: Abstract classes:
- Objects cannot be created for the abstract classes.
- If a class has only one method as abstract, then that class must be an abstract class.
- The child class which extends an abstract class must define all the methods of the abstract class.
- If the abstract method is defined as protected in the parent class, the function implementation must be defined as either protected or public, but not private.
- The signatures of the methods must match, the optional parameter given in the child class will not be accepted and error will be shown.
- Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).
Difference between abstract class and interface.
| Abstract class | Interface |
|
It can have constants, members, method stubs (methods without a body), methods |
It can only have constants and methods stubs. |
|
Methods and members can have public or protected visibility
|
Methods of the interface should only be public not any other visibility |
|
The concept of multiple inheritances not supported.
|
An interface can extend or a class can implement multiple other interfaces. |
|
Child class must implement all the abstract methods of parent class when extend keyword is used.
|
No need of implementing methods from parent interface when interface is extending another interface |
