Home  >  Article  >  Backend Development  >  PHP Basic Tutorial 12: Abstraction and Interface

PHP Basic Tutorial 12: Abstraction and Interface

黄舟
黄舟Original
2017-03-01 10:04:091253browse

Content explained in this section

  • Abstract

  • Interface

  • Use of final

  • Class constants

Preface

Object-oriented in PHP is to instantiate objects by defining classes, and PHP's abstract classes and interface classes can be said to be a specification of classes. Classes are defined by defining these two classes. Mandatory constraints, although both are constraints on classes, they are essentially different.

Abstract class

We can use the inheritance relationship of animals to illustrate the concept of abstract classes. When we write the parent class Animal class, there are two methods sleep (), eat(), because I don’t know the specific animal, I can’t determine what is written in the method. This can be achieved using abstract classes.

<?php
//通过关键字abstract来声明抽象类
abstract class Animal{
    protected $name;
    protected $age;
    //声明该方法是抽象方法
    abstract public function sleep();
    abstract public function eat();
}

When some methods of the parent class cannot be determined, the abstract keyword can be used to modify the method, which is called an abstract method, and the class modified with abstract is called an abstract class.

Basic syntax:

abstract  class  类名{
    abstract  访问修饰符   函数名(参数列表);
}

In development, when we want all subclasses that inherit this class to override the methods of this class, we can use abstract methods to achieve this. An abstract class is like a shelf for something, or a template. With a template, you can implement specific functions based on the template. , and the relationship between templates and specific things is passed through inherited classes. Just like a computer, computers are made through templates. Abstract classes are defined and need to be inherited.

<?php

abstract class Animal{
    protected $name;
    protected $age;

    abstract public function sleep();
    abstract public function eat();
}
class Dog extends Animal{

}
......结果........
Fatal error: Class Dog contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Animal::sleep, Animal::eat) 
in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\chouxiang.php on line 13

When a class inherits an abstract class, all abstract methods of the parent class need to be implemented in the subclass The error reported above means that the parent class contains 2 abstract methods , subclasses must implement this abstract method. The characteristics of abstract classes can be summarized as follows:

  • Abstract classes cannot be instantiated. If you cannot create a new object through an abstract class, a Cannot instantiate abstract class error will be reported.

  • There is no need for abstract methods in abstract classes. All methods in abstract classes are ordinary methods, but the class name is modified with abstract.

    <?php
    abstract class Animal{
        protected $name;
        protected $age;
        public function sleep(){
    
        }
        public function eat(){
    
        }
    }
  • Abstract classes can have ordinary member methods, properties, etc.

    <?php
    abstract class Animal{
        protected $name;
        protected $age;
    
        abstract public function sleep();
        abstract public function eat();
    
        public function cry(){
    
        }
    }
  • If there are abstract methods in a class, then the class must be abstract class.

  • Abstract methods have no method body

    abstract public function eat();

    There is no {}, which means there is no method body.

  • If a class inherits an abstract class, the subclass must implement all abstract methods of the abstract class, or the subclass itself must be declared as an abstract class

Interface

The original intention of the interface is the same as that of the abstract class. When you don’t know how to implement the method, you can use the interface to implement it. The definition of interface is: give some unimplemented methods, encapsulate them together, and then write these methods according to the specific situation when a certain class is used. The emergence of interfaces reflects the characteristics of high cohesion and low coupling.

<?php

interface iTechnical{
    public function fly();
}

Basic syntax:

interface 接口名{
    //方法, 在接口中,所有的方法都不能有方法体, 即都是抽象方法
}

Interface classes are roughly the same as abstract classes, so what exactly is an interface? It is mentioned above that abstract classes are like the shelves and templates of a notebook, and then specific notebooks are created based on the templates. No notebook has several USB interfaces, and the interface class is like the interface on these notebooks, which is an extended implementation. . Just like animals, they inherit the unique characteristics of animals such as eating, sleeping, etc., but suddenly an animal realizes the ability to write elsewhere, and this ability is expanded through interfaces.

The naming of the interface generally starts with the first letter of the class name, which is lowercase i. All methods in interface classes are abstract methods by default. So there is no need to write abstract to declare.

Implementation of interface

When we define an interface, of course we let other classes implement it. What we are talking about here is implementation, not inheritance, interface and other classes. There is an implementation relationship between them, that is, the class implements a certain interface and is implemented using the implements keyword.

interface iTechnical{
    public function fly();
}

class Dog implements iTechnical{
    public function fly(){
        echo &#39;<br>飞&#39;;
    }
}

Of course, all methods in the interface must be implemented in the subclass.

The following are the characteristics of interfaces:

  • Interface classes, like abstract classes, cannot be instantiated.

  • All methods in the interface cannot have a body because they are all abstract methods.

  • A class can implement multiple interfaces, separated by commas (inheritance can only be one)

    class Dog implements 接口1,接口2{
    
    }
  • The interface can have attributes, but It can only be a constant, the default is public, but it cannot be explicitly modified with public

  • All methods in the interface must be public. The interface is for inheritance, so use public. If not Write modifiers, the default is public

  • An interface cannot inherit other classes, but it can inherit other interfaces

Abstract and The difference between interfaces

Inheritance in PHP is single inheritance, that is, a class can only have one parent class at most. This single inheritance mechanism can ensure the purity of the class. However, this mechanism has a certain impact on the function expansion of subclasses.

接口的出现可以说是对继承的一种补充,继承是层级的,不太灵活,而接口却没有它比抽象要灵活的多。并且实现接口在不打破继承关系的前提下,对子类的功能进行扩充。
它们两个的关系图可以理解为这样:
PHP Basic Tutorial 12: Abstraction and Interface

final的使用

在上面的介绍中每个类都是可以被继承的,如果我们有一个类,我们不想让子类去重写里面的某个方法,或者不想让别的类去继承该类,就可以用到关键字final。final中文意思:最后的,最终的,可以用来修饰类或者方法。

final可以修饰方法或者类,如果修饰方法,则表示该方法不可以被继承类去重写,如果final 修饰了一个类,则表示该类不可以被继承。

基本语法:

final  class   类名{
}
class 类名{
    final 访问修饰符 function 函数名(形参){}
}

修饰类和修饰方法。

<?php

    final class A{

    }

    class B extends A{

    }
    .....结果.....
    Class B may not inherit from final class (A)

不能继承用final修饰的类。

<?php

    class A{
        final public function sum($num1,$num2){
            return $num1 + $num2;
        }

    }

    class B extends A{
        public function sum($num1,$num2){
            return $num1 + $num2;
        }
    }
    .....结果.....
    Cannot override final method A::sum()

从结果中可以看出来不能重写用final定义的方法。

在使用final时,只能用来修饰类或者方法,不能修饰属性。当一个类被final修饰后,类中的方法就不需要被final修饰,因为类都不能继承了,方法就不能重写。同时final修饰的类是可以被实例化的。

如果一个方法被final修饰,是可以被继承的,但是不能被重写。

<?php

    class A{
        final public function sum($num1,$num2){
            return $num1 + $num2;
        }

    }

    class B extends A{

    }

    $b = new B();
    echo $b -> sum(1,2);
    .......结果.......
    3

在我们写单例模式时,说过当时的单例模式是不完善的,可以通过继承来得到不同的对象,在这里我们使用final关键字修饰单例类,防止继承,这样就不能通过继承的到别的对象。

类常量

类常量和普通的常量是一个概念,当不希望一个成员变量被修改,希望该变量的值是固定不变的。这时可以用const去修饰该成员变量,这样这个变量就自动成为常量。在类中的常量称为类常量。前面我们讲过定义常量有两种方式define()和关键字const,在类中必须使用const这种方式,使用define()是会报错的。

<?php

    class A{
        const PI = 3.1415926;

        public function getPI(){
            return A::PI;
        }
    }

    $a = new A();
    echo $a -> getPI();
    echo &#39;<br>&#39;;
    echo A::PI;
    ......结果......
    3.1415926
    3.1415926

类常量的命名一般是全部用大写字母,中间用下划线隔开,同时常量前面没有$符号。常量必须在定义的时候就赋值。同时常量的前面不能有修饰符,默认是public。

常量的访问形式

常量的访问形式分为两种,一种是在类的内部进行访问,一种是在类的外部进行访问。

内部访问

通过 类名::常量名进行访问。

class A{
    const PI = 3.1415926;

    public function getPI(){
        return A::PI;//通过类名进行访问
    }
}

通过 self::常量名进行访问

class A{
    const PI = 3.1415926;

    public function getPI(){
        return self::PI;//通过类名进行访问
    }
}

可以通过self进行访问说明常量是属于类的,并不属于对象的。

外部访问

通过类名::常量名访问。

echo A::PI;

通过对象名::常量名访问

$a = new A();
echo $a::PI;

不过推荐使用第一种,通过类名进行访问。

如果一个类中有常量,则在继承的时候常量也是可以被继承的。同时常量的数据类型不能是对象。

总结

PHP中抽象和接口应用让我们的更加清楚的把握需求的骨架,更好的搭建我们的代码体系。同时利用抽象和接口降低代码的耦合度。利于代码的扩展。

 以上就是PHP基础教程十二之抽象、接口的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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