Home  >  Article  >  Backend Development  >  PHP object-oriented programming (oop) study notes (1) - abstract classes, object interfaces, instanceof and contract programming_PHP tutorial

PHP object-oriented programming (oop) study notes (1) - abstract classes, object interfaces, instanceof and contract programming_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:28:261079browse

1. Abstract class in PHP

PHP 5 supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class must be declared abstract if at least one method in it is declared abstract. A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation. A class can be declared abstract by using the abstract modifier in its declaration.

It can be understood that an abstract class serves as a base class and leaves specific details to successors. By abstracting concepts, you can create scalable architectures in your development projects.

Copy code The code is as follows:

abstract class AbstractClass
{
code...
}

1.1, Abstract method

Use the abstract keyword to define abstract methods. Abstract methods only retain the method prototype (the signature after the method body is removed from the method definition), which includes access levels, function keywords, function names and parameters. It does not contain ({}) or any code inside brackets. For example, the following code is an abstract method definition:

Copy code The code is as follows:

abstract public function prototypeName($protoParam);

When inheriting an abstract class, the subclass must define all abstract methods in the parent class; in addition, the access control of these methods must be the same (or more relaxed) as in the parent class. In addition, the method calling methods must match, that is, the type and number of required parameters must be consistent.

1.2. About abstract classes

A class must be declared as an abstract class as long as it contains at least one abstract method.
Methods declared as abstract must contain the same or lower access level when implemented.
Instances of abstract classes cannot be created using the new keyword.
Methods declared as abstract cannot contain function bodies.
If the extended class is also declared as an abstract class, you do not need to implement all abstract methods when extending the abstract class. (If a class inherits from an abstract class, it must also be declared abstract when it does not implement all abstract methods declared in the base class.)
1.3. Use abstract classes

Copy code The code is as follows:

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.对象接口

使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。

接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。

接口中定义的所有方法都必须是公有,这是接口的特性。

接口是一种类似于类的结构,可用于声明实现类所必须声明的方法。例如,接口通常用来声明API,而不用定义如何实现这个API。

大多数开发人员选择在接口名称前加上大写字母I作为前缀,以便在代码和生成的文档中将其与类区别开来。

2.1接口实现(implements)

要实现一个接口,使用 implements 操作符(继承抽象类需要使用 extends 关键字不同),类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。

实现多个接口时,接口中的方法不能有重名。
接口也可以继承,通过使用 extends 操作符。
类要实现接口,必须使用和接口中所定义的方法完全一致的方式。否则会导致致命错误。
接口中也可以定义常量。接口常量和类常量的使用完全相同,但是不能被子类或子接口所覆盖。
2.2使用接口的案例

复制代码 代码如下:

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

instanceof 运算符是 PHP5 中的一个比较操作符。他接受左右两边的参数,并返回一个boolean值。

确定一个 PHP 变量是否属于某个一类 CLASS 的实例
检查对象是不是从某个类型继承
检查对象是否属于某个类的实例
确定一个变量是不是实现了某个接口的对象的实例

复制代码 代码如下:

echo $Porsche911 instanceof Car;
//result:1

echo $Porsche911 instanceof ISpeendInfo;
//result:1

4.Contract Programming

Design by Contract or Design by Contract (DbC) is a method of designing computer software. This method requires software designers to define formal, precise and verifiable interfaces for software components. In this way, a priori conditions, a posteriori conditions and invariants are added to traditional abstract data types. The "contract" or "contract" used in the name of this method is a metaphor because it is somewhat similar to the situation of a business contract.

A programming practice of implementing a declared interface before writing a class. This method is very useful in ensuring the encapsulation of classes. Using contract programming techniques, we can define the functionality of a view before creating an application, much like an 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 implementation of the declared methods. To declare a method as abstract, simply remove the method entity containing all curly braces and end the line of code where the method is declared 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 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 interfaces cannot declare any methods with method bodies; and the syntax they use is also different. In order to force uncovering rules on 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 specific class, or whether it implements a specific interface. instanceof is suitable for this task. instanceof checks three things: whether the instance is of a specific type, whether the instance inherits from a specific type, and whether the instance or any of its ancestor classes implement a class-specific interface.

Some languages ​​have the ability to inherit from multiple classes, this is called multiple inheritance. PHP does not support multiple inheritance. The idea is that it provides the function of declaring multiple interfaces for a class.

Interfaces are useful for declaring rules that a class must follow. Contractual programming technology uses this feature to enhance encapsulation and optimize workflow.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/788637.htmlTechArticle1. Abstract classes in PHP PHP 5 supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class, if at least one method in it is declared abstract...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn