PHP - Using Inheritance to Extend the Power of Objects

Introduction

To create a child class that's based on a parent class, you use the extends keyword, as follows:

<?php
        class Shape {
          // (General Shape properties and methods here)
         }

        class Circle extends Shape {
          // (Circle-specific properties and methods here)
         }
?>

It creates a parent Shape class, holding properties and methods common to all shapes.

Then it creates two child classes based on Shape - Circle and Square - that contain properties and methods related to circles and squares, respectively.

Demo

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

           public function getColor() {
             return $this->_color;//from  ww  w  .  j  a va  2 s. com
           }

           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;
           }
          }

         class Circle extends Shape {
           private $_radius = 0;

           public function getRadius() {
             return $this->_radius;
           }

           public function setRadius($radius) {
             $this->_radius = $radius;
           }

           public function getArea() {
             return M_PI * pow($this->_radius, 2);
           }
          }

         class Square extends Shape {
           private $_sideLength = 0;

           public function getSideLength() {
             return $this->_sideLength;
           }

           public function setSideLength($length) {
             $this->_sideLength = $length;
           }
  public function getArea() {
    return pow($this->_sideLength, 2);
  }
}

$myCircle = new Circle;
$myCircle->setColor("red");
$myCircle->fill();
$myCircle->setRadius(4);
echo "My Circle \n";
echo "My circle has a radius of". $myCircle->getRadius().".\n";
echo "It is". $myCircle->getColor()."and it is". ($myCircle->
isFilled() ?"filled":"hollow").".\n";
echo "The area of my circle is:". $myCircle->getArea().".\n";

$mySquare = new Square;
$mySquare->setColor("green");
$mySquare->makeHollow();
$mySquare->setSideLength(3);
echo "My Square \n";
echo "My square has a side length of". $mySquare->getSideLength(). ".\n";
echo "It is". $mySquare->getColor()."and it is". ($mySquare->isFilled() ?"filled":"hollow").". < /p >";

echo "The area of my square is:". $mySquare->getArea().".\n";
?>

Result

Related Topic