×
☰ See All Chapters

PHP Abstract Class

A class which is declared with abstract keyword is called abstract class.

abstract class ClassName{

    //members of abstract class

}

Abstract class is used to do partial implementation and setting the standards for the subclasses to do the implementation. Abstract class may contain both concrete and abstract functions. But if a class has an abstract function, then the class should be declared as abstract. A class containing all concrete functions can be declared as abstract. This is done generally if you do not want to create an instance of a particular class.

An abstract function is a function that is declared without an implementation (without braces, and followed by a semicolon).

abstract AccessSpecifier  function functionName($pmtr1, $pmtr2, $pmtr3...)  : returnType;

 

When an abstract class is sub classed, the subclass must override the abstract function and provide implementation for all of the abstract functions of its parent class. If it does not, the subclass must also be declared abstract. Any number of classes can implement abstract class. To implement abstract class, implementation class has to extend the abstract class.

class ImplementationClass extends Abstractclass {

    // implementation for abstract class abstract methods

}

 

Abstract Class Example

<?php

// Parent class

abstract class Fruit {

    public $name;

    public function __construct($name) {

        $this->name = $name;

    }

    abstract public function printName() : string;

}

 

// Child classes

class Apple extends Fruit {

    public function printName() : string {

        return "I am $this->name!";

    }

}

 

class Mango extends Fruit {

    public function printName() : string {

        return "I am $this->name!";

    }

}

 

$apple = new Apple("Apple");

echo $apple->printName();

echo "<br>";

 

$mango = new Mango("Mango");

echo $mango->printName();

echo "<br>";

 

?>

php-abstract-class-0
 

All Chapters
Author