PHP Objects Interfaces
ADVERTISEMENTS
An object interface is a set of a code block of using methods, which defines which methods must implement in the class, which class uses this interface.
How to declare an interface
Interface declaration is the same as a class declaration, but there are uses interface keyword instead of the class keyword. It does not declare any method but It calls methods, which will be declared in the associated class.
Note:
- It is possible to declare a constructor in an interface, which can be useful in some contexts, e.g. for use by factories.
- To implement an interface, there is a need interface operator to implement this.
- To successfully run a program all methods of interfaces must be declared in the class. Otherwise, It will occur a FATAL error.
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.
- Interfaces can be extended like classes using the extends operator.
- 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.
Example-1: implementing a class with a single interface
<?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;
}
}
?>
Example-2: Implementing a class with multiple interfaces
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// This will work
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// This will not work and result in a fatal error
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
How to implement the interface with 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.
<?php
interface a
{
const b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;
// This will however not work because it's not allowed to
// override constants.
class b implements a
{
const b = 'Class constant';
}
?>