Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is an abstract class in PHP?

Dario Vincenzo Tarantini

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 class
abstract class Person {

  protected $name;
  
  // this is a normal function that will be inheritate by our class
  public function setName(string $newName){
    $this->name = $newName;
  }
  // this abstract function doesent have a body
  // it need to be implemented inside our class
  abstract 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 abstract methods, we need to define them too.

<?php 
// we will use the previous code
abstract class Person {
  protected $name;
  public function setName(string $newName) {
    $this->name = $newName;
  }
  abstract public function printName();
}

// let's define a standard class extending Person
class MyPerson extends Person {
    public function printName() {
        echo $this->name . "\n";
    }
}

// this finally work
$mp = new MyPerson();
$mp->setName("Educative");
$mp->printName();

RELATED TAGS

php
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring