This paper introduces a simple implementation method of PHP object interface. The details are as follows:
Using interface, you can specify which methods a class must implement, but you don’t need to define the specific contents of these methods.
The interface is defined by the interface keyword, just like a standard class, but all the methods defined in it are empty.
All methods defined in an interface must be public, which is a feature of the interface.
Implementation
To implement an interface, use the implements operator. Class must implement all the methods defined in the interface, otherwise a fatal error will be reported. Class can implement multiple interfaces, with a comma to separate the names of multiple interfaces.
Note:
When implementing multiple interfaces, methods in an interface cannot have duplicate names.
Note:
Interfaces can also be inherited by using the extensions operator.
Note:
To implement an interface, a class must use exactly the same way as the method defined in the interface. Otherwise, it will lead to fatal error.
Examples
<?php
//Declare an 'ITemplate' interface
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
//Implementation interface
//The following is correct
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;
}
}
More about PHP related content, interested readers can see the special topics of this website: “PHP object-oriented programming introductory tutorial”, “PHP array operation skills encyclopedia”, “PHP basic grammar introductory tutorial”, “PHP operation and operator Usage Summary”, “PHP string Usage Summary”, “PHP + MySQL database operation introductory tutorial” and “PHP common database operation” Summary of writing skills
I hope this article is helpful for PHP programming.