Introduction to PHP - Abstract Methods Part 2

Guest Posts Paolo Nikko Nuñal

In the last article we talk about the how abstract class work and how they can be beneficial when you are going to structure your code. Lets go back again with the example.

<?php
abstract class Stats{
  private $intelligence;
  private $strength;
  private $agility;

  abstract function statSheet();
  abstract function setStats($intelligence,$strength,$agility);
  }

class Hero extends Stats{
  public function statSheet(){
     echo "Intelligence: ".$this->intelligence."<br>";
     echo "Strength: ".$this->strength."<br>";
     echo "Agility: ".$this->agility."<br>";
  }
  public function setStats($intelligence,$strength,$agility){
    $this->intelligence = $intelligence * 2;
    $this->strength = $strength * 0.35;
    $this->agility = $agility * 23;
  }
}

 class Minion extends Stats{
    private $life;
    private $mana;

    public function statSheet(){
       echo "Life: ".$this->life."<br>";
       echo "Mana: ".$this->mana."<br>";
    }
    public function setStats($intelligence,$strength,$agility){
       $this->life = $strength * 24;
       $this->mana = $intelligence * 12.35;
    }
 }


  $jaina = new Hero;
  $jaina->setStats(1,2,3);
  echo "Hero Stats:<br>";
  echo $jaina->statSheet();

  $minion = new Minion;
  $minion->setStats(2,3,4);
  echo "Minion Stats:<br>";
  echo $minion->statSheet();
?>


Based from the example above we have created another class called Minion in which it also extends to the abstract class Stats. As you can see it still uses the 2 abstract methods declared on the Stats class.

As a recap, an abstract class is used as a "guide" for the programmer on how to implement the method. From the two classes, the Hero and the Minion class both have the two abstract methods but have different implementation. That pretty much defines that abstract classes have abstract methods that don't have a body since it is up to the programmer on how the functions should behave. This will  prove useful as you can later add or edit some functionality.