Introduction to PHP OPP mechanisms and patterns (abstract classes interfaces and contractual programming)

  • 2021-06-28 12:00:37
  • OfStack

1. Abstract Classes

An abstract class mechanism always defines a common base class, leaving specific details to the inheritor to implement.By using abstract concepts, you can create scalable architectures in your development projects.Any class in which at least one method is declared abstract must be declared abstract.A method defined as abstract simply declares how it is invoked (parameters), not its specific functional implementation.A class can be declared abstract by using the abstract modifier in its declaration.

1.1 Method Prototype (prototype)

The signature after the body of the method has been removed from the definition of the method.It includes access levels, function keywords, function names, and parameters.He does not contain ({}) or any code inside parentheses.For example, the following code is a method prototype:


public function prototypeName($protoParam)

When inheriting an abstract class, the subclass must define all the abstract methods in the parent class.In addition, access control for these methods must be the same (or more relaxed) as in the parent class.

1.2 About abstract classes

A class must be declared abstract as long as it contains at least one abstract method
Methods declared abstract must be implemented with the same or lower access level.
Instances of abstract classes cannot be created using the new keyword.
Methods that are abstracted by life cannot contain function bodies.
If the extended class is also declared as an abstract class, all abstract methods may not be implemented when extending the abstract class. (If a class inherits from an abstract class, it must also be declared abstract if it does not implement all the abstract methods declared in the base class.)

1.3 Use abstract classes


<?php
abstract class Car
{    
    abstract function getMaxSpeend();
}
class Roadster extends Car
{
    public $Speend;
    public function SetSpeend($speend = 0)
    {
        $this->Speend = $speend;
    }
    public function getMaxSpeend()
    {
        return $this->Speend;
    }
}
class Street
{
    public $Cars ;
    public $SpeendLimit ;
    function __construct( $speendLimit = 200)
    {
        $this -> SpeendLimit = $speendLimit;
        $this -> Cars = array();
    }

    protected function IsStreetLegal($car)
    {
        if ($car->getMaxSpeend() < $this -> SpeendLimit)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public function AddCar($car)
    {
        if($this->IsStreetLegal($car))
        {
            echo 'The Car was allowed on the road.';
            $this->Cars[] = $car;
        }
        else
        {
            echo 'The Car is too fast and was not allowed on the road.';
        }
    }
}
$Porsche911 = new Roadster();
$Porsche911->SetSpeend(340);
$FuWaiStreet = new Street(80);
$FuWaiStreet->AddCar($Porsche911);
/**
 *
 * @result
 * 
 * The Car is too fast and was not allowed on the road.[Finished in 0.1s]
 *
 */
?>

2. Object Interface

Using an interface (interface), you can specify which methods a class must implement, but you do not need to define the specific content of those methods.

Interfaces are defined by the interface keyword, just like a standard class 1, but all methods defined in it are empty.

All methods defined in an interface must be public, which is a property of the interface.

Interfaces are a class-like structure that can be used to declare methods that must be declared to implement a class.For example, interfaces are often used to declare API without defining how to implement it.

Most developers choose to prefix the interface name with the capital letter I to distinguish it from the class in code and generated documents.

2.1 Use interfaces

Unlike the extends keyword required to integrate Abstract classes, the implements keyword is used to implement the interface.A class can implement multiple interfaces, in which case we need to separate them with commas.If a class is marked as implementing an interface but not all methods for that excuse, an error will be thrown.

2.2 Cases of using interfaces


<?php
abstract class Car
{    
    abstract function SetSpeend($speend = 0);
}
interface ISpeendInfo
{
    function GetMaxSpeend();
}
class Roadster extends Car implements ISpeendInfo
{
    public $Speend;
    public function SetSpeend($speend = 0)
    {
        $this->Speend = $speend;
    }
    public function getMaxSpeend()
    {
        return $this->Speend;
    }
}
class Street
{
    public $Cars ;
    public $SpeendLimit ;
    function __construct( $speendLimit = 200)
    {
        $this -> SpeendLimit = $speendLimit;
        $this -> Cars = array();
    }
    protected function IsStreetLegal($car)
    {
        if ($car->getMaxSpeend() < $this -> SpeendLimit)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public function AddCar($car)
    {
        if($this->IsStreetLegal($car))
        {
            echo 'The Car was allowed on the road.';
            $this->Cars[] = $car;
        }
        else
        {
            echo 'The Car is too fast and was not allowed on the road.';
        }
    }
}

$Porsche911 = new Roadster();
$Porsche911->SetSpeend(340);
$FuWaiStreet = new Street(80);
$FuWaiStreet->AddCar($Porsche911);
/**
 *
 * @result
 * 
 * The Car is too fast and was not allowed on the road.[Finished in 0.1s]
 *
 */
?>

3.instanceof Operator

The instanceof operator is a comparison operator in PHP5.He accepts both left and right arguments and returns an boolean value.This operator is used to determine whether an instance of an object is of a particular type, inherits from a type, or implements a particular interface of a class.


echo $Porsche911 instanceof Car;
//result : 1
echo $Porsche911 instanceof ISpeendInfo;
//result : 1

4. Contractual programming

Contractual programming is a programming practice that implements a declarative interface before writing a class.This method is very useful in ensuring the encapsulation of classes.Using contractual programming, we can define what the view does before creating the application, much like the way the architect draws a blueprint before building a building.

5. Summary

Abstract classes are classes declared using the abstract keyword.By marking a class as abstract, we can defer the implementation of the declared method.To declare a method as abstract, simply remove the method entity that contains all braces and end the line of code declared by the method with a semicolon.

Abstract classes cannot be instantiated directly; they must be inherited.

If a class inherits from an abstract class, it must also be declared abstract if it does not implement all the abstract methods declared in the base class.

In an interface, we can declare a method prototype without a method body, much like an abstract class.The difference between them is that an interface cannot declare any method with a method body;And they use the same grammar.In order to force the unveiling rules onto a class, we need to use the implements keyword instead of the extends keyword.

In some cases, we need to determine whether a class is of a particular type or whether it implements a particular interface.instanceof is divided into groups suitable for this task.instanceof checks three things: whether an instance is of a particular type, whether it inherits from a particular type, and whether an instance or any of its ancestor classes implement class-specific interfaces.

Some languages have the ability to inherit from multiple classes, which is called multiple inheritance.PHP does not support multiple inheritance.Ideas, he provides the ability to declare multiple interfaces for a class.

Interfaces are useful when declaring rules that classes must follow.Contractual programming uses this feature to enhance encapsulation and optimize workflow.


Related articles: