What is an abstract class in PHP?
In PHP, the abstract keyword is used to define:
- Classes that can’t be instantiated
- Methods without implementation
Abstract classes and methods
An abstract class is used to extend a class that imports public, private, protected, and abstract methods.
Every abstract methods defined in the abstract class must be implemented inside the extended class. This is useful when we need to define a common structure between different classes.
An abstract class with an abstract method is defined like this:
<?php// let's define an abstract classabstract class Person {protected $name;// this is a normal function that will be inheritate by our classpublic function setName(string $newName){$this->name = $newName;}// this abstract function doesent have a body// it need to be implemented inside our classabstract public function printName();}try{// this will fail: we cant instantiate an abstract class$ac = new Person();}catch(\Exception $e){var_dump($e);}
The code above throws an exception because abstract classes can not be instantiated.
How to use it
If we want to use the abstract class, we have to create a new class and extend it with our abstract class:
Note: If there is any
abstractmethods, we need to define them too.
<?php// we will use the previous codeabstract class Person {protected $name;public function setName(string $newName) {$this->name = $newName;}abstract public function printName();}// let's define a standard class extending Personclass MyPerson extends Person {public function printName() {echo $this->name . "\n";}}// this finally work$mp = new MyPerson();$mp->setName("Educative");$mp->printName();