Interface¶
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 may have methods signatures, without a body, and constants.
<?php
// Declare the interface 'Template'
interface Template
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class WorkingTemplate implements Template
{
private $vars = [];
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;
}
}
?>
See also Interfaces vs Abstract Classes in PHP, Interfaces - the misunderstood concept, Granular interfaces, When to add an interface to a class, Code to an interface!
Related : Fluent Interface