Detailed Explanation of the Difference Example between PHP Abstract Class and Interface

  • 2021-12-11 17:23:11
  • OfStack

This article illustrates the difference between PHP abstract classes and interfaces. Share it for your reference, as follows:

Abstract class abstract

Concept

Classes defined as abstractions cannot be instantiated. Any 1 class, if 1 method is declared abstract, then the class must be declared abstract.

When inheriting an abstract class, the subclass must define all the abstract methods in the parent class, and the access control of these methods must be the same as or looser than that in the parent class.

For example, if an abstract method is declared as proteced, the implementation in the subclass should be declared as protected or public, but not as private.

Methods must be called in a matching manner, i.e. the type and required number of parameters must be 1. For example, if a subclass defines an optional parameter and the parent class does not declare it in an abstract method, the declarations of the two do not conflict.

Characteristic

Abstract class inheritance, using the keyword extends. Abstract classes can declare various variables, constants and methods. Abstract classes can have constructors. Methods in abstract classes can be exposed public, protected protected, and private private. A class can inherit only one abstract class.

Example

Example 1


<?php
//  Abstract class 
abstract class AbstractClasss
{
  //  Force subclasses to define these methods 
  abstract protected function getValue();
  abstract protected function prefixValue();
  //  Common method (non-abstract method) 
  public function printOut() 
  {
    print $this->getValue() . "\n";
  }
}
//  Subclass 
class ConcreteClassOne extends AbstractClass
{
  protected function getValue()
  {
    return "ConcreteClassOne";
  }
  public function prefixValues($prefix)
  {
    return "{$prefix}ConcreteClassOne";
  }
}
//  Subclass 
class ConcreteClassTwo extends AbstractClass
{
  protected function getValue()
  {
    return "ConcreteClassTwo";
  }
  public function prefixValue($prefix)
  {
    return "{$prefix}ConcreteClassTwo";
  }
}
//  Instantiate the 1 Subclass 
$classOne = new ConcreteClassOne;
$classOne->printOut();
echo $classOne->prefixValue('FOO_') . "\n";
//  Instantiate the 2 Subclass 
$classTwo = new ConcreteClassTwo;
$classTwo->printOut();
echo $classTwo->prefixValue('FOO_') . "\n";

Result output

ConcreteClassOne
FOO_ConcreteClassOne

ConcreteClassTwo
FOO_ConcreteClassTwo

Example 2


<?php
//  Abstract class 
abstract class AbstractClass
{
  //  Our abstract method only needs to define the required parameters 
  abstract protected function prefixName($name);
}
//  Subclass 
class ConcreteClass extends AbstractClass
{
  //  Our subclass can define optional parameters that do not exist in the parent class signature 
  public function prefixName($name, $separator = ".")
  {
    if ($name == "Pacman") {
      $prefix = "Mr";
    } elseif ($name == "Pacwoman") {
      $prefix = "Mrs";
    } else {
      $prefix = "";
    }
    return "{$prefix}{$separator} {$name}";
  }
}
//  Instantiate a subclass 
$class = new ConcreteClass;
echo $class->prefixName("Pacman") . "\n";
echo $class->prefixName("Pacwoman") . "\n";

Result output

Mr. Pacman
Mrs, Pacwoman

Interface interface

Concept

Using the interface interface, you can specify which methods a class must implement, but you don't need to define the details of these methods.

To implement an interface, using the implements operator, all the methods defined in the interface must be implemented in the class.

Characteristic

Interface, using the keyword implements. You cannot declare variables in the interface, but you can declare constants. There is no constructor in the interface. The methods in the interface are exposed public by default. One class can implement multiple interfaces.

Example

Example 1, Implementing an Interface


<?php
//  Declaration 1 A iTemplate Interface 
interface iTemplate
{
  public function setVariable($name, $var);
  public function getHtml($template);
}
//  Implementation interface 
//  The following writing 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;
  }
}
//  The following writing is wrong and will report an error because it is not implemented  getHtml()
// Fatal error: Class BadTemplate contains 1 abstract methonds
// and must therefore be declared abstaract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
  private $vars = array();
  public function setVariable($name, $var)
  {
    $this->vars[$name] = $var;
  }
}

Example 2, Extensible Interface


<?php
interface a
{
  public function foo();
}
interface b extends a
{
  public function baz(Baz $baz);
}
//  Correct writing 
class c implements b
{
  public function foo()
  {
  }
  public function baz(Baz $baz)
  {
  }
}
//  Wrong writing will lead to 1 A fatal mistake 
class d implements b
{
  public function foo()
  {
  }
  public function baz(Foo $foo)
  {
  }
}

Example 3, Inheriting Multiple Interfaces


<?php
interface a
{
  pubLic function foo();
}
interface b
{
  public function bar();
}
interface c extends a, b
{
  public function baz();
}
class d implements c
{
  public function foo()
  {
  }
  public function bar()
  {
  }
  public function baz()
  {
  }
}

Example 4, Using Interface Constants


<?php
interface a
{
  const b = 'Interface constant';
}
//  Output interface variable 
echo a:b;
//  Wrong writing, because constants cannot be overridden. 
//  The concept of interface constants and the concept of class constants are 1 Like it. 
class b implements a
{
  const b = 'Class constant'
}

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this paper is helpful to everyone's PHP programming.


Related articles: