Interfaces – the abstract class

An interface, as described further on the php.net website here, is basically a abstract class that defines a skeleton of what a class will have to at least implement, this allows for classes to implement a set skeleton and you will know what functions that class will have to implement.

The interface is just that, a skeleton of a base class. e.g. a interface could be a shape, and the classes that implement the interface called shape could be circle, square etc..because they will all have the basic functions for example, shape sides, colour etc.

Here is some php code, I always find looking over code easier to understand the basics of things.

<?php
 
/* this is a adstract class, e.g. any class that implements this class will have to implement all of the 
  skeleton functions that this class as defined 
 
  the abstract class is defined with the "interface" type */
 
interface Skeleton {
    public function printOutAWord($theWord);
 
    public function printOutAArray($theArray);
}
 
/* 
  this class, TheWorker, will actually "implement" the abstract class Skeleton, via the 
  implemets syntax  */
 
class TheWorker implements Skeleton {
    // these are the functions code that was defined by the abstract class.
    public function printOutAWord($theWord)
    {
	echo "\n$theWord\n";
    }
 
    public function printOutAArray($theArray)
    {
	echo "\n". print_r($theArray)."\n";
    }
}
 
$newWorker = new TheWorker();
 
$newWorker->printOutAWord("Printing out a word");
 
$newWorker->printOutAArray(array("Array","words","are","here"));
?>

And the output would be this

Printing out a word
Array
(
    [0] => Array
    [1] => words
    [2] => are
    [3] => here
)

Leave a Reply

Your email address will not be published. Required fields are marked *