PHP Object Oriented Programming (oop) Learning Notes of 1 Abstract Classes Object Interfaces instanceof and Contractual Programming

  • 2021-06-29 10:29:32
  • OfStack

1. Abstract Classes in PHP

PHP 5 supports abstract classes and methods.Classes defined as abstract cannot be instantiated.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.

It can be understood that an abstract class is a base class that leaves specific details to its inheritors to implement.By using abstract concepts, you can create scalable architectures in your development projects.


abstract class AbstractClass
{
    code...
}

1.1. Abstract Method

Use the abstract keyword to define an abstract method.An abstract method retains only the method prototype (the signature after the method body is removed from the method definition), which includes access level, function keywords, function name, and parameters.He does not contain ({}) or any code inside parentheses.For example, the following code is an abstract method definition:


abstract 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.In addition, methods must be called in a way that matches the type and number of required parameters.

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 declared abstract 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. Using 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.

The interface is 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 Interface Implementation (implements)

To implement an interface, use the implements operator (inheriting abstract classes requires different extends keywords), which must implement all methods defined in the interface, or a fatal error will be reported.Classes implement multiple interfaces and use commas to separate the names of multiple interfaces.

When implementing multiple interfaces, methods in an interface cannot have duplicate names.
Interfaces can also be inherited by using the extends operator.
Classes must implement interfaces in a manner that is exactly the same as the method defined in the interface.Otherwise, it will result in a fatal error.
Constants can also be defined in interfaces.Interface constants and class constants are used exactly the same, but cannot be overridden by subclasses or subinterfaces.
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. Type Operator instanceof

The instanceof operator is a comparison operator in PHP5.He accepts both left and right arguments and returns an boolean value.

Determines whether an PHP variable belongs to an instance of a class 1 CLASS
Check whether the object inherits from a type
Check whether an object belongs to an instance of a class
Determines if a variable is an instance of an object that implements an interface


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

4. Contractual programming

Contractual design or Design by Contract (DbC) is a method of designing computer software.This approach requires software designers to define formal, accurate, and verifiable interfaces for software components, thus adding a priori, a posteriori, and an invariant to traditional abstract data types.The term "contract" or "contract" used in the name of this method is a metaphor because it is somewhat similar to the case of a commercial contract.

A programming practice for implementing declarative interfaces before writing classes.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 a particular type, whether it inherits from a particular type, and whether an instance or any of its ancestor classes implement a class-specific interface.

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: