PHP - Using Abstract Classes and Methods

Introduction

Abstract classes and methods can lay down some ground rules about how a child class should behave

When you declare an abstract method, you don't insert any code in the method; instead, you leave that up to the child classes.

To declare an abstract method, simply use the abstract keyword, as follows:

abstract public function myMethod($param1, $param2);

You can optionally specify any parameters that the method must contain.

However, you don't include any code that implements the method, nor do you specify what type of value the method must return.

If you declare one or more methods of a class to be abstract, you must also declare the whole class to be abstract, too:

abstract class MyClass {
    abstract public function myMethod($param1, $param2);
}

You can't instantiate an abstract class - that is, create an object from it - directly:

// Generates an error:"Cannot instantiate abstract class MyClass"
$myObj = new MyClass;

So when you create an abstract class, you are essentially creating a template, rather than a fully fledged class.

Your abstract class might define behavior that is common to all possible child classes, while leaving the remainder of the methods abstract for the child classes to implement.

Demo

<?php
abstract class Shape {
           private $_color ="black";
           private $_filled = false;

           public function getColor() {
             return $this->_color;/*  w  w w.  j a va2  s.c  o m*/
           }
      public function setColor($color) {
        $this->_color = $color;
      }

      public function isFilled() {
        return $this->_filled;
      }

      public function fill() {
        $this->_filled = true;
      }

      public function makeHollow() {
        $this->_filled = false;
      }

      abstract public function getArea();
    }
    class Rectangle extends Shape {
      private $_width = 0;
      private $_height = 0;

      public function getWidth() {
        return $this->_width;
      }

      public function getHeight() {
        return $this->_height;
      }

      public function setWidth($width) {
        $this->_width = $width;
      }

      public function setHeight($height) {
        $this->_height = $height;
      }
           public function getArea() {
             return $this->_width * $this->_height;
           }
          }

$myRect = new Rectangle;
$myRect->setColor("yellow");
$myRect->fill();
$myRect->setWidth(4);
$myRect->setHeight(5);
?>

Related Topic