PHP tutorial: abstract class and interface

PHP tutorial: abstract class and interface


OOP in PHP

Abstract class and interface

An abstract class allows you to define member variables and methods. You can choose to write body for the method or just leave it blank. The abstract can be inherited. It prohibits creation of object. In PHP, to define an abstract class, you must you the abstract keyword. A method of the abstract class can be or cannot be overridden by its sub-classes. If you place the abstract keyword before the method's name, this method must be overridden by its sub-classes. In the example code below, People is an abstract class. The Student class inherits member variables and method from the abstract class. The printInfo method is marked as abstract so that it must be overridden by the Student class.

<?php

abstract class People{
protected $name;
protected $sex;
abstract function printInfo();


}

class Student extends People{
private $id;
function Student($name,$sex,$id){
  $this->name=$name;
  $this->sex=$sex;
  $this->id=$id;
}
function printInfo(){
  echo "Name:".$this->name. "<br />";
  echo "Sex:".$this->sex. "<br />";
  echo "Id:".$this->id. "<br />";

}
}

$st=new Student("Dara SK","M",1010);
$st->printInfo();

?>

Another element of OOP that you should understand is interface. In PHP, you can define an interface by using the interface keyword. An interface outlines the actions or behaviors that a class must have. All methods defined in the interface must be overriden by the class the implements that interface. You will use the implements keyword to implement the interface. For example, a TV class must override the switchOn and switchOff methods defined in the Switchable interface.

<?php
interface Switchable{
  public function switchOn();
  public function switchOff();
}

class TV implements Switchable{
private $roomName;
function TV($roomName){
  $this->roomName=$roomName;
}
function switchOn(){
  echo "TV in room ".$this->roomName." is on.<br />";
}
function switchOff(){
  echo "TV in room ".$this->roomName." is off.<br />";
}

}
?>



Comments

Tomás Díaz comment

 Tomás Díaz

Really nice tutorial, nothing like real life examples...

Nice to meet you and happy 2014.


2013-12-30




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.