DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Abstract Classes in PHP

To understand abstract classes we can use an example which uses shapes.

First off, we will create the following folder structure.

Alt Text

And after, lets see whats in each of those files,

In the shapefeatures.abstract.php file we will have the following written

<?php

abstract class ShapeFeatures {

  public function getBackgroundColour(){
      return "Color";
  }   

}

In the Triangle.class.php file we'll have the following

<?php

Class Triangle extends ShapeFeatures{

  public function FindColor(){
            return $this-> getBackgroundColour();
        } 

    }

And in the index.php file we will have this,

<?php 

include_once "abstract/shapefeatures.abstract.php";
include_once "classes/Triangle.class.php";

$tri = new Triangle();
echo $tri -> FindColor();
?>

So you can see we extend Triangle to shapefeatures- And we don't create an object of shapefeatures, and when we extend a class to an abstract class all the features of the abstract class is available to it , hence we can easily do what we've done in the index.php file (ie. successfully execute findColor() from the triangle object which has a method thats declared in the abstract class )

Please note that this example is used as it makes it easier to understand the use of abstract class, once you understand the concept of abstract classes I recommend checking out https://phpenthusiast.com/blog/the-decorator-design-pattern-in-php-explained and more resources.

Top comments (2)

Collapse
 
danielbenzie profile image
Daniel

This is not a good example of an abstract class.

In your example you are adding another method to call the abstract parent method. You could (and should) just call that method directly... otherwise you are still implementing duplicate functionality across all of your child classes and you may as well just have used an interface.

Collapse
 
naveenkolambage profile image
Naveen Dinushka

Hmm sure