What are Abstract classes?
If you want to write a class only to inherit the class and not to create the objects of the class, then abstract classes do that job for you.
- You cannot create the objects or instances of an abstract class.
- Properties and methods of abstract classes can only be accessed through child classes.
How to create Abstract classes in PHP?
PHP OOP has a keyword called abstract
which is used to turn a class into an abstract class.
You have to write this abstract
keyword before the class
keyword like the following syntax –
abstract class ClassName{
// Properties and Methods
}
Example of Abstract Class
<?php
abstract class MyAbsClass{
private $name = 'John';
public function sayHello(){
echo "Hello ".$this->name;
}
}
class MyClass extends MyAbsClass{
function __construct()
{
$this->sayHello();
}
}
$obj = new MyClass();
/**
❌ You cannot do this
$obj = new MyAbsClass();
*/
Hello John
Abstract methods in PHP OOP
You can also create abstract methods with the help of the abstract
keyword.
Few rules for creating abstract methods
- You can create abstract methods only inside the abstract classes.
- You cannot describe the body of the the abstract methods inside the abstract class. You are only allowed to declare the the abstract method inside the abstract class.
- You must have to describe the body of the abstract methods inside the child classes.
<?php
abstract class MyAbsClass{
// Declaring the SayHello Function
abstract function sayHello($a);
}
class MyClass extends MyAbsClass{
// Describing the body of the SayHello Function
function sayHello($name){
echo "Hello $name";
}
}
$obj = new MyClass();
$obj->sayHello('Mark');
Important notes for abstract methods
1. Abstract methods cannot be declared private
. It could be public
or protected
.
// ❌ Wrong - you cannot do this
abstract private function sayHello($a);
// ✔️ Right Way
abstract public function sayHello($a);
// OR - It is also right ✔️
abstract protected function sayHello($a);
2. The access modifier of an abstract method must be the same or weaker in the child class.
Abstract Class | Child Class |
---|---|
public | public |
protected | protected or public |
abstract protected function sayHello($a);
// ❌ Wrong
private function sayHello($name){
echo "Hello $name";
}
// ✔️ Right Way
public function sayHello($name){
echo "Hello $name";
}
// OR - It is also right ✔️
protected function sayHello($name){
echo "Hello $name";
}