Open In App

Abstract Classes in PHP

Last Updated : 15 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Abstract classes in PHP are classes that may contain at least one abstract method. Unlike C++, abstract classes in PHP are declared using the abstract keyword. The purpose of abstract classes is to enforce that all derived classes implement the abstract methods declared in the parent class. An abstract class can contain abstract as well as non-abstract methods.

php
<?php 
abstract class Base 
{ 
    abstract function printdata(); 
    function pr() 
    { 
        echo "Base class"; 
    } 
} 

class Derived extends Base 
{ 
    function printdata() { 
        echo "Derived class"; 
    } 
} 

// Creating an object of Derived class
$b1 = new Derived; 
$b1->printdata(); 
?>

Output
Derived class

Important Facts About Abstract Classes in PHP

1. Cannot Create Instances of an Abstract Class

Like Java, an instance of an abstract class cannot be created in PHP.

PHP
<?php
abstract class Base {
    abstract function printdata();
}
class Derived extends base {
    function printdata() {
        echo "Derived class";
    }
}

// Uncommenting the following line will cause a fatal error:
// $b = new Base();   
    
$b1 = new Derived;
$b1->printdata();
?>

Output
Derived class

2. Abstract Classes Can Have Constructors

Like in C++ and Java, abstract classes in PHP can have constructors.php

PHP
<?php 

abstract class Base { 
    function __construct() { 
        echo "This is an abstract class constructor"; 
    } 

    abstract function printdata(); 
} 

class Derived extends Base { 
    function __construct() { 
        echo "\nDerived class constructor"; 
    } 
    
    function printdata() { 
        echo "\nDerived class printdata function"; 
    } 
} 

$b1 = new Derived; 
$b1->printdata(); 

?>

Output
Derived class constructor
Derived class printdata function

3. Abstract Methods Cannot Have a Body in PHP

Unlike Java, PHP does not allow an abstract method to have a body.

PHP
<?php
abstract class Base {
    abstract function printdata() {
        echo "Parent class printdata";
    }
}
?>

Output
Fatal error: Abstract function Base::printdata() cannot contain body in /home/guest/sandbox/Solution.php on line 3

Corrected Example

PHP
<?php
abstract class Base { 
    abstract function printdata(); 
}
?>

Next Article

Similar Reads