Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented.

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.

All methods declared in an interface must be public; this is the nature of an interface.

Note that it is possible to declare a constructor in an interface, what can be useful in some contexts, e.g. for use by factories.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note:

Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

Note:

Interfaces can be extended like classes using the extends operator.

Note:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Constants

It's possible for interfaces to have constants. Interface constants work exactly like class constants except they cannot be overridden by a class/interface that inherits them.

Examples

Example #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
  
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }
 
        return 
$template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}
?>

Example #2 Extendable Interfaces

<?php
interface a
{
    public function 
foo();
}

interface 
extends a
{
    public function 
baz(Baz $baz);
}

// This will work
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

<?php
interface a
{
    public function 
foo();
}

interface 
b
{
    public function 
bar();
}

interface 
extends ab
{
    public function 
baz();
}

class 
implements c
{
    public function 
foo()
    {
    }

    public function 
bar()
    {
    }

    public function 
baz()
    {
    }
}
?>

Example #4 Interfaces with constants

<?php
interface a
{
    const 
'Interface constant';
}

// Prints: Interface constant
echo a::b;


// This will however not work because it's not allowed to 
// override constants.
class implements a
{
    const 
'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.

add a note add a note

User Contributed Notes 41 notes

up
863
dlovell2001 at yahoo dot com
6 years ago
It seems like many contributors are missing the point of using an INTERFACE. An INTERFACE is not specifically provided for abstraction. That's what a CLASS is used for. Most examples in this article of interfaces could be achieved just as easily using just classes alone.

An INTERFACE is provided so you can describe a set of functions and then hide the final implementation of those functions in an implementing class. This allows you to change the IMPLEMENTATION of those functions without changing how you use it.

For example: I have a database. I want to write a class that accesses the data in my database. I define an interface like this:

interface Database {
function listOrders();
function addOrder();
function removeOrder();
...
}

Then let's say we start out using a MySQL database. So we write a class to access the MySQL database:

class MySqlDatabase implements Database {
function listOrders() {...
}
we write these methods as needed to get to the MySQL database tables. Then you can write your controller to use the interface as such:

$database = new MySqlDatabase();
foreach ($database->listOrders() as $order) {

Then let's say we decide to migrate to an Oracle database. We could write another class to get to the Oracle database as such:

class OracleDatabase implements Database {
public function listOrders() {...
}

Then - to switch our application to use the Oracle database instead of the MySQL database we only have to change ONE LINE of code:

$database = new OracleDatabase();

all other lines of code, such as:

foreach ($database->listOrders() as $order) {

will remain unchanged. The point is - the INTERFACE describes the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works.
up
164
koalay at gmail dot com
4 years ago
Just wrote some examples of duck-typing in PHP. Sharing here.

<?php

/**
* An example of duck typing in PHP
*/

interface CanFly {
  public function
fly();
}

interface
CanSwim {
  public function
swim();
}

class
Bird {
  public function
info() {
    echo
"I am a {$this->name}\n";
    echo
"I am an bird\n";
  }
}

/**
* some implementations of birds
*/
class Dove extends Bird implements CanFly {
  var
$name = "Dove";
  public function
fly() {
    echo
"I fly\n";
  }
}

class
Penguin extends Bird implements CanSwim {
  var
$name = "Penguin";
  public function
swim() {
    echo
"I swim\n";
  }
}

class
Duck extends Bird implements CanFly, CanSwim {
  var
$name = "Duck";
  public function
fly() {
    echo
"I fly\n";
  }
  public function
swim() {
    echo
"I swim\n";
  }
}

/**
* a simple function to describe a bird
*/
function describe($bird) {
  if (
$bird instanceof Bird) {
   
$bird->info();
    if (
$bird instanceof CanFly) {
     
$bird->fly();
    }
    if (
$bird instanceof CanSwim) {
     
$bird->swim();
    }
  } else {
    die(
"This is not a bird. I cannot describe it.");
  }
}

// describe these birds please
describe(new Penguin);
echo
"---\n";

describe(new Dove);
echo
"---\n";

describe(new Duck);
up
7
Chris AT w3style DOT co.uk
12 years ago
Note that you can extend interfaces with other interfaces since under-the-hood they are just abstract classes:

<?php

interface Foo {
    public function
doFoo();
}

interface
Bar extends Foo {
    public function
doBar();
}

class
Zip implements Bar {
    public function
doFoo() {
        echo
"Foo";
    }
    public function
doBar() {
        echo
"Bar";
    }
}

$zip = new Zip();
$zip->doFoo();
$zip->doBar();

?>

This is quite useful when you're using interfaces for identity more than the rigidity it places upon an API.  You can get the same result by implementing multiple interfaces.

An example of where I've used this in the past is with EventListener objects ala Java's Swing UI.  Some listeners are effectively the same thing but happen at different times therefore we can keep the same API but change the naming for clarity.
up
12
Hayley Watson
11 years ago
If it's not already obvious, it's worth noticing that the parameters in the interface's method declaration do not have to have the same names as those in any of its implementations.

More significantly, default argument values may be supplied for interface method parameters, and they have to be if you want to use default argument values in the implemented classes:

<?php
interface isStuffable
{
    public function
getStuffed($ratio=0.5);
}

class
Turkey implements isStuffable
{
    public function
getStuffed($stuffing=1)
    {
       
// ....
   
}
}
?>

Note that not only do the parameters have different names ($ratio and $stuffing), but their default values are free to be different as well. There doesn't seem to be any purpose to the interface's default argument value except as a dummy placeholder to show that there is a default (a class implementing isStuffable will not be able to implement methods with the signatures getStuffed(), getStuffed($a), or getStuffed($a,$b)).
up
10
Vasiliy Makogon
4 years ago
The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error. -- this documentation page.

But, if you use default values in arguments in methods, fatal error is not follow:

<?php
interface myInterface {
    public function
__construct();
}

class
concret implements myInterface {

    public function
__construct($arg=null)
    {
       
print_r(func_get_args());
    }
}

$obj = new concret(123);
?>

Array ( [0] => 123 )
up
40
erik dot zoltan at msn dot com
13 years ago
When should you use interfaces?  What are they good for?
Here are two examples. 

1. Interfaces are an excellent way to implement reusability. 
You can create a general interface for a number of situations
(such as a save to/load from disk interface.)  You can then
implement the interface in a variety of different ways (e.g. for
formats such as tab delimited ASCII, XML and a database.) 
You can write code that asks the object to "save itself to
disk" without having to worry what that means for the object
in question.  One object might save itself to the database,
another to an XML and you can change this behavior over
time without having to rewrite the calling code. 

This allows you to write reusable calling code that can work
for any number of different objects -- you don't need to know
what kind of object it is, as long as it obeys the common
interface. 

2. Interfaces can also promote gradual evolution.  On a
recent project I had some very complicated work to do and I
didn't know how to implement it.  I could think of a "basic"
implementation but I knew I would have to change it later. 
So I created interfaces in each of these cases, and created
at least one "basic" implementation of the interface that
was "good enough for now" even though I knew it would have
to change later. 

When I came back to make the changes, I was able to create
some new implementations of these interfaces that added the
extra features I needed.  Some of my classes still used
the "basic" implementations, but others needed the
specialized ones.  I was able to add the new features to the
objects themselves without rewriting the calling code in most
cases.  It was easy to evolve my code in this way because
the changes were mostly isolated -- they didn't spread all
over the place like you might expect.
up
19
Hayley Watson
11 years ago
On an incidental note, it is not necessary for the implementation of an interface method to use the same variable names for its parameters that were used in the interface declaration.

More significantly, your interface method declarations can include default argument values. If you do, you must specify their implementations with default arguments, too. Just like the parameter names, the default argument values do not need to be the same. In fact, there doesn't seem to be any functionality to the one in the interface declaration at all beyond the fact that it is there.

<?php
interface isStuffed {
    public function
getStuff($something=17);
}

class
oof implements isStuffed {
    public function
getStuff($a=42) {
        return
$a;
    }
}

$oof = new oof;

echo
$oof->getStuff();
?>

Implementations that try to declare the method as getStuff(), getStuff($a), or getStuff($a,$b) will all trigger a fatal error.
up
13
tkostantinov
5 years ago
Implementation must be strict, subtypes are not allowed.

"The class implementing the interface must use the EXACT SAME METHOD SIGNATURES as are defined in the interface. Not doing so will result in a fatal error. "

<?php

interface I
{
  function
foo(stdClass $arg);
}

class
Test extends stdClass
{
}

class
Implementation implements I
{
  function
foo(Test $arg)
    {
    }
}
?>
Result:

Fatal error: Declaration of InterfaceImplementation::foo() must be compatible with I::foo(stdClass $arg) in test.php on line XY
up
3
mehea
10 years ago
While a subclass may implement an interface by extending an abstract class that implements the interface, I question whether it is good design to to do so.  Here's what I would suggest while taking the liberty of modifying the above weather/wet model:

<?php
interface water
{
    public function
makeItWet();
}


/**
   * abstract class implements water but defines makeItWet
   * in the most general way to allow child class to
   * provide specificity
**/
abstract class weather implements water                   
{
   private
$cloudy;
   public function
makeItWet(){}
   abstract public function
start();
   abstract public function
getCloudy();
   abstract public function
setCloudy();
}

class
rain extends weather                            {
    private
$cloudy;   
    public function
start() {
        return
"Here's some weather. ";
    }
   
    public function
makeItWet() {
        return
'it is raining cats and dogs today.';
    }
    public function
getCloudy() {
        return
$this->cloudy;
    }
    public function
setCloudy($bln=false) {
       
$this->cloudy = $bln;
    }
}

$a = new rain();
echo
$a->start();
$a->setCloudy(true);
if (
$a->getCloudy()) {
    echo
'It is a cloudy day and ';
}
echo
$a->makeItWet();

?>
up
3
Maikel
12 years ago
if you want to implement an interface and in addition to use inheritance, first it uses “extends” and then “implements” example:

<?php
class MyChildClass extends MyParentClass implements MyInterface
{
  
// definition
}
?>
up
4
russ dot collier at gmail dot com
14 years ago
You can also specify class constants in interfaces as well (similar to specifying 'public static final' fields in Java interfaces):

<?php

interface FooBar
{

    const
SOME_CONSTANT = 'I am an interface constant';

    public function
doStuff();

}

?>

Then you can access the constant by referring to the interface name, or an implementing class, (again similar to Java) e.g.:

<?php

class Baz implements FooBar
{

   
//....

}

print
Baz::SOME_CONSTANT;
print
FooBar::SOME_CONSTANT;

?>

Both of the last print statements will output the same thing: the value of FooBar::SOME_CONSTANT
up
12
thanhn2001 at gmail dot com
7 years ago
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const
b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class
b implements a
{
}

// This works!!!
class c extends b
{
    const
b = 'Class constant';
}

echo
c::b;
?>
up
10
uramihsayibok, gmail, com
8 years ago
Interfaces can define static methods, but note that this won't make sense as you'll be using the class name and not polymorphism.

...Unless you have PHP 5.3 which supports late static binding:

<?php

interface IDoSomething {
    public static function
doSomething();
}

class
One implements IDoSomething {
    public static function
doSomething() {
        echo
"One is doing something\n";
    }
}

class
Two extends One {
    public static function
doSomething() {
        echo
"Two is doing something\n";
    }
}

function
example(IDoSomething $doer) {
   
$doer::doSomething(); // "unexpected ::" in PHP 5.2
}

example(new One()); // One is doing something
example(new Two()); // Two is doing something

?>

If you have PHP 5.2 you can still declare static methods in interfaces. While you won't be able to call them via LSB, the "implements IDoSomething" can serve as a hint/reminder to other developers by saying "this class has a ::doSomething() method".
Besides, you'll be upgrading to 5.3 soon, right? Right?

(Heh. I just realized: "I do something". Unintentional, I swear!)
up
6
drieick at hotmail dot com
8 years ago
I was wondering if implementing interfaces will take into account inheritance. That is, can inherited methods be used to follow an interface's structure?

<?php

interface Auxiliary_Platform {
    public function
Weapon();
    public function
Health();
    public function
Shields();
}

class
T805 implements Auxiliary_Platform {
    public function
Weapon() {
       
var_dump(__CLASS__);
    }
    public function
Health() {
       
var_dump(__CLASS__ . "::" . __FUNCTION__);
    }
    public function
Shields() {
       
var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

class
T806 extends T805 implements Auxiliary_Platform {
    public function
Weapon() {
       
var_dump(__CLASS__);
    }
    public function
Shields() {
       
var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

$T805 = new T805();
$T805->Weapon();
$T805->Health();
$T805->Shields();

echo
"<hr />";

$T806 = new T806();
$T806->Weapon();
$T806->Health();
$T806->Shields();

/* Output:
string(4) "T805"
string(12) "T805::Health"
string(13) "T805->Shields"
<hr />string(4) "T806"
string(12) "T805::Health"
string(13) "T806->Shields"
*/

?>

Class T805 implements the interface Auxiliary_Platform. T806 does the same thing, but the method Health() is inherited from T805 (not the exact case, but you get the idea). PHP seems to be fine with this and everything still works fine. Do note that the rules for class inheritance doesn't change in this scenario.

If the code were to be the same, but instead T805 (or T806) DOES NOT implement Auxiliary_Platform, then it'll still work. Since T805 already follows the interface, everything that inherits T805 will also be valid. I would be careful about that. Personally, I don't consider this a bug.

This seems to work in PHP5.2.9-2, PHP5.3 and PHP5.3.1 (my current versions).

We could also do the opposite:

<?php

class T805 {
    public function
Weapon() {
       
var_dump(__CLASS__);
    }
}

class
T806 extends T805 implements Auxiliary_Platform {
    public function
Health() {
       
var_dump(__CLASS__ . "::" . __FUNCTION__);
    }
    public function
Shields() {
       
var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

$T805 = new T805();
$T805->Weapon();

echo
"<hr />";

$T806 = new T806();
$T806->Weapon();
$T806->Health();
$T806->Shields();

/* Output:
string(4) "T805"
<hr />string(4) "T805"
string(12) "T806::Health"
string(13) "T806->Shields"
*/

?>

This works as well, but the output is different. I'd be careful with this.
up
5
aditycse at gmail dot com
3 years ago
Solution for overriding interface constants
//we can override interface constants by using  abstract class
//if Test Class implements inter1 than we can not override inter1 interface constants
example:

<?php

interface inter1 {

    const
interface1 = "I am from interface 1";

    function
foo1();

    function
bar1();
}

interface
inter2 extends inter1 {

    function
foo2();

    function
bar2();
}

interface
inter3 {

    function
foo3();

    function
bar3();
}

interface
inter4 {

    function
foo4();

    function
bar4();
}

abstract class
AbsClass implements inter2 {
   
}

class
Test extends AbsClass implements inter3, inter4 {

    const
interface1 = "I am from test class";

    public function
foo1() {
       
    }

    public function
foo2() {
       
    }

    public function
foo3() {
       
    }

    public function
foo4() {
       
    }

    public function
bar1() {
       
    }

    public function
bar2() {
       
    }

    public function
bar3() {
       
    }

    public function
bar4() {
       
    }

    public function
display() {
        echo
inter1::interface1;
        echo
PHP_EOL;
        echo
Test::interface1;
    }

}

$Obj = new Test();
$Obj->display(); //I am from interface 1 \n I am from test class
up
7
Vladimir Kornea
5 years ago
By asking your colleague to implement your interface, you are asking him to guarantee that he has implemented all the methods you need. He can implement multiple interfaces, each being a contract, so that the guy cleaning up the cruft down the road can see which methods belong to which area of concern; but since interfaces are primarily contracts rather than documentation, a class cannot implement two interfaces containing the same method since that would make the contract lose credibility through ambiguity. Thus a class can implement two interfaces with overlapping concerns only by factoring their common methods into a third interface that serves as a base for the first two, which resolves the contractual ambiguity.
up
5
secure_admin
10 years ago
In response to harryjry and mehea concerning your Weather Model. The problem is that you don't need all the things you think you need. In OOP, good class definitions get to the point rather quickly.

<?php
class Weather{
  public
$time, $temperature, $humidity;

  public function
__construct($tm, $t, $h){
   
$this->time = $tm;
   
$this->temperature = $t;
   
$this->humidity = $h;
  }

  public function
__toString(){
    return
"Time: $this->time,
      Temperature:
$this->temperature&deg;,
      Humidity:
$this->humidity