Sunday, November 17, 2024
Google search engine
HomeLanguagesAbstract Classes in PHP

Abstract Classes in PHP

Abstract classes are the classes in which at least one method is abstract. Unlike C++ abstract classes in PHP are declared with the help of abstract keyword. Use of abstract classes are that all base classes implementing this class should give implementation of abstract methods declared in parent class. An abstract class can contain abstract as well as non abstract methods.




<?php
  
// Abstract class example in PHP
abstract class base
{
    // This is abstract function
    abstract function printdata();
      
    // This is not abstract function
    function pr()
    {
        echo "Base class";
    }
}
?>


Following are some important facts about abstract classes in PHP.

  • Like Java, PHP also an instance of abstract class can not be created.

    Example:




    <?php
      
    // Abstract class
    abstract class Base {
        // This is abstract function
        abstract function printdata();
    }
    class Derived extends base {
        function printdata() {
            echo "Derived class";
        }
    }
      
    // Uncommenting the following line will 
    // cause compiler error as the line tries
    // to create an instance of abstract class. 
    // $b = new Base(); 
          
    $b1 = new Derived;
    $b1->printdata();
    ?>

    
    
    Output:

    Derived class
    
  • Like C++ or Java abstract class in PHP can contain constructor also.

    Example:




    <?php
      
    // Abstract class
    abstract class Base {
        function __construct() {
            echo "this is abstract class constructor ";
        }
      
        // This is abstract function
        abstract function printdata();
    }
    class Derived extends base {
        function __construct() {
            echo "\n Derived class constructor";
        }
        function printdata() {
            echo "\n Derived class printdata function";
        }
    }
    $b1 = new Derived;
    $b1->printdata();
    ?>

    
    
    Output:

    Derived class constructor
     Derived class printdata function
    
  • Unlike Java, an abstract class can not be created which does not contains at least one abstract method in PHP. If we run the following example then it will display an error message.

    Example:




    <?php
      
    // example to understand that an abstract 
    // class can not contain an method with
    // body in php
    abstract class Base {
        abstract function printdata() {
            echo "Parent class printdata";
        }
    }
    ?>

    
    

    Runtime Errors:

    PHP Fatal error:  Abstract function Base::printdata() cannot contain body 
    in /home/a7540402ade5337d505a779cf4797b38.php on line 7
    

RELATED ARTICLES

Most Popular

Recent Comments