Introduction to PHP opp mechanisms and patterns (abstract class, interface, and contract programming) _php Instance

Source: Internet
Author: User
Tags inheritance

1. Abstract class

The abstract class mechanism always defines a common base class, and the specific details are left to the successor to implement. Abstract concepts allow you to create an extensible architecture in your development project. Any class, if at least one of its methods is declared abstract, then the class must be declared abstract. A method that is defined as abstract simply declares its invocation mode (parameters) and cannot define its specific function implementation. You can declare a class as abstract by using the abstract modifier in the declaration of a class.

1.1 Method Prototypes (prototype)

means that the signature of the method body is excluded from the definition of the method. It includes access levels, function keywords, function names, and parameters. He does not contain ({}) or any code inside the brackets. For example, the following code is a method prototype:

Copy Code code as follows:

Public Function Prototypename ($protoParam)

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 (or looser) as in the parent class.

1.2 About abstract Classes

A class must be declared as an abstract class as long as it contains at least one abstract method
A method declared as abstract must contain the same or lower access level at the time of implementation.
You cannot use the New keyword to create an instance of an abstract class.
A method that is abstract by life cannot contain a function body.
If you also declare an extended class as an abstract class, you can extend the abstract class without implementing all of the abstract methods. (If a class inherits from an abstract class, it must also be declared abstract when it does not implement all of the abstract methods declared in the base class.) )

1.3 Using abstract Classes

Copy Code code as follows:

<?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 =)
    {
         $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 ' car is allowed on the road. '
$this->cars[] = $car;
}
Else
{
Echo ' car is too fast and am not allowed on the road. '
}
}
}

$Porsche 911 = new Roadster ();
$Porsche 911->setspeend (340);

$FuWaiStreet = New Street (80);
$FuWaiStreet->addcar ($Porsche 911);

/**
*
* @result
*
* The car is too fast and am not allowed on the road. [Finished in 0.1s]
*
*/
?>

2. Object interface

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

Interfaces are defined by interface keywords, just like defining a standard class, but all of the methods defined are empty.

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

An interface is a class-like structure that can be used to declare the methods that the implementation class must declare. For example, an interface is typically used to declare an API without having to define how to implement the API.

Most developers choose to prefix the interface names with uppercase I, so that they distinguish them from classes in the code and in the resulting document.

2.1 Using Interfaces

and the integration abstract class needs to use the extends keyword, the implementation interface uses the Implements keyword. A class can implement multiple interfaces, at which point we need to separate them with commas. If you mark a class as implementing an interface, but you do not have all the methods to implement that excuse, you will throw an error.

2.2 Cases using the interface

Copy Code code as follows:

<?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 ' car is allowed on the road. '
$this->cars[] = $car;
}
Else
{
Echo ' car is too fast and am not allowed on the road. '
}
}
}


$Porsche 911 = new Roadster ();
$Porsche 911->setspeend (340);

$FuWaiStreet = New Street (80);
$FuWaiStreet->addcar ($Porsche 911);

/**
*
* @result
*
* The car is too fast and am not allowed on the road. [Finished in 0.1s]
*
*/
?>

3.instanceof operator

The instanceof operator is a comparison operator in PHP5. He accepts arguments on both sides of the argument and returns a Boolean value. This operator is used to determine whether an instance of an object is a specific type, or whether it inherits from a type, or implements a particular interface of the class.

Copy Code code as follows:

Echo $Porsche 911 instanceof car;
Result:1

Echo $Porsche 911 instanceof Ispeendinfo;
Result:1

4. Contract-Type programming

Contract programming refers to a programming practice of implementing a declaration interface before writing a class. This method is useful in guaranteeing the encapsulation of a class. Using the contract programming technique, we can define the functionality of the view implementation before the application is created, which is very similar to the way architects draw blueprints before building buildings.

5. Summary

An abstract class is a class declared using the abstract keyword. By marking a class as an abstract class, we can postpone the implementation of the declared method. To declare a method as an abstract method, simply remove the method entity that contains all the braces, and end the line of the method declaration 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 when it does not implement all of the abstract methods declared in the base class.

In an interface, we can declare a method prototype without a method body, which is very similar to an abstract class. The difference between them is that an interface cannot declare any method with a method body, and they use a different syntax. In order to force the uncover rule 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 a type of a particular class, or whether a particular interface is implemented. Instanceof partitioning is suitable for accomplishing this task. Instanceof examines three things: whether an instance is a particular type, whether an instance inherits from a particular type, or whether an instance or any of his 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. Idea, he provides the ability to declare multiple interfaces for a class.

Interfaces are useful when declaring a rule that a class must follow. This function is used by the contract programming technology to enhance the encapsulation and optimize the workflow.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.