In PHP, we can create an abstract class by using an abstract keyword. When we create an abstract class then there are some rules.
- An abstract class contains at least one abstract method.
- An abstract method is defined but not used or not implemented.
- The number of required arguments must be the same.
- We cannot create an object of an abstract class.
Example1 ( Simple class )
<?php
class car{
public $name;
public function __construct($name){
echo $this->name=$name;
}
}
$obj= new car("Audi");
?>
Output
Audi
Example2 ( abstract class )
<?php
abstract class car{
public $name;
public function __construct($name){
echo $this->name=$name;
}
}
$obj= new car("Audi");
?>
Output
Note: we cannot create an object of an abstract class.
Let’s see another example where abstract class A is created and at least one abstract show() method is declared but not implemented.
It is implemented in the child class, not the parent class.
Example 3
Example 4
<?php
// Parent class
abstract class Fruit {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
// Child classes
class Apple extends Fruit {
public function intro() : string {
return "I like $this->name!";
}
}
class Banana extends Fruit {
public function intro() : string {
return "I like $this->name!";
}
}
class Grapes extends Fruit {
public function intro() : string {
return "I like $this->name!";
}
}
// Create objects from the child classes
$obj1 = new Apple("Apple");
echo $obj1->intro();
echo "<br>";
$obj2= new Banana("Banana");
echo $obj2->intro();
echo "<br>";
$obj3 = new Grapes("Grapes");
echo $obj3->intro();
?>
Prev Next