Simple implementation of PHP object interface

Time:2021-1-17

This paper introduces a simple implementation method of PHP object interface. The details are as follows:

Object interface

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.

Recommended Today

JavaScript animation example: rotated equilateral triangle

Given that the coordinates of the center of gravity of an equilateral triangle are (x0, Y0) and the height is h, you can draw an equilateral triangle with horizontal bottom edge with the following statement.          ctx.beginPath();          ctx.moveTo(x0,y0-h*2/3);          ctx.lineTo(x0+h/Math.sqrt(3), y0+h/3);           ctx.lineTo(x0-h/Math.sqrt(3), y0+h/3);          ctx.lineTo(x0,y0-h*2/3);          ctx.closePath();          ctx.stroke(); Given the number of […]