Home Backend Development PHP Tutorial Detailed explanation of php interface and abstract class usage example code

Detailed explanation of php interface and abstract class usage example code

Jul 03, 2017 am 09:29 AM
php code Example

1. Abstract classabstract class

1. An abstract class refers to a class with the abstract keyword added before class and an abstract method (abstract keyword added before the class method function keyword).

2 . Abstract classes cannot be instantiated directly. The abstract class only defines (or partially implements) the methods required by the subclass. Subclasses can make an abstract class concrete by inheriting it and by implementing all the abstract methods in the abstract class.

3. If a subclass needs to be instantiated, it must implement all abstract methods in the abstract class. If the subclass does not implement all abstract methods in the abstract class, then the subclass is also an abstract class and must be preceded by the abstract keyword in class and cannot be instantiated.

The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

abstract class

    /** 抽象类中可以定义变量 */

    protected $value1 = 0; 

    private $value2 = 1; 

    public $value3 = 2; 

    /** 也可以定义非抽象方法 */

    public function my_print() 

    

        echo "hello,world/n"

    

    /**

     * 大多数情况下,抽象类至少含有一个抽象方法。抽象方法用abstract关键字声明,其中不能有具体内容。

     * 可以像声明普通类方法那样声明抽象方法,但是要以分号而不是方法体结束。也就是说抽象方法在抽象类中不能被实现,也就是没有函数体“{some codes}”。

     */

    abstract protected function abstract_func1(); 

    abstract protected function abstract_func2(); 

abstract class B extends 

    public function abstract_func1() 

    

       echo "implement the abstract_func1 in class A/n"

    

    /** 这么写在zend studio 8中会报错*/

    //abstract protected function abstract_func2(); 

class C extends

    public function abstract_func2() 

    

       echo "implement the abstract_func2 in class A/n"

    

}

Copy after login

4. If you create a subclass B that inherits from A as shown below, but does not implement the abstract method abstract_func():

The code is as follows:

1

Class B extends A{};

Copy after login

Then the program will have the following error:

The code is as follows:

1

Fatal error: Class B contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (A::abstract_func)

Copy after login

5. If B implements the abstract method abstract_func(), then the access control of the abstract_func() method in B cannot be stricter than the access control of abstract_func() in A, that is to say:

( 1) If abstract_func() in A is declared as public, then the declaration of abstract_func() in B can only be public, not protected or private

(2) If abstract_func() in A is declared as protected, then The declaration of abstract_func() in B can be public or protected, but cannot be private

(3) If abstract_func() in A is declared as private, hehe, it cannot be defined as private! (Fatal error: Abstract function A::abstract_func() cannot be declared private)

2. Interface interface

1. Abstract classes provide standards for concrete implementation, while interfaces are pure templates. Interfaces only define functions, not implementation content. Interfaces are declared with the keyword interface.

2 . Interface is completely abstract. It can only declare methods, and only public methods. It cannot declare private and protected methods, cannot define method bodies, and cannot declare instance variables. However, interfaces can declare constant variables. But placing constant variables in an interface violates its purpose of existing as an interface, and also confuses the different values ​​of interfaces and classes. If you really need it, you can put it in the corresponding abstract class or Class.

The code is as follows:

1

2

3

4

5

6

7

interface iA 

    const AVAR=3; 

    public function iAfunc1(); 

    public function iAfunc2(); 

echo iA:: AVAR;

Copy after login

3. Any class that implements an interface must implement all methods defined in the interface

The code is as follows:

1

2

3

4

5

class E implements iA 

    public function iAfunc1(){echo "in iAfunc1";} 

    public function iAfunc2(){echo "in iAfunc2";} 

}

Copy after login

Otherwise the class must be declared abstract.

The code is as follows:

1

abstract class E implements iA{}

Copy after login

4. A class can implement an interface using the implements keyword in its declaration. After doing this, the specific process of implementing the interface is the same as inheriting an abstract class that only contains abstract methods. A class can inherit a parent class and implement any number of interfaces at the same time. The extends clause should precede the implements clause. PHP only supports inheritance from one parent class, so the extends keyword can only be followed by a class name.

The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

interface iB 

    public function iBfunc1(); 

    public function iBfunc2(); 

class D extends A implements iA,iB 

    public function abstract_func1() 

    

       echo "implement the abstract_func1 in class A/n"

    

    public function abstract_func2() 

    

       echo "implement the abstract_func2 in class A/n"

    

    public function iAfunc1(){echo "in iAfunc1";} 

    public function iAfunc2(){echo "in iAfunc2";} 

    public function iBfunc1(){echo "in iBfunc1";} 

    public function iBfunc2(){echo "in iBfunc2";} 

class D extends B implements iA,iB 

    public function abstract_func1() 

    

       parent::abstract_func1(); 

       echo "override the abstract_func1 in class A/n"

    

    public function abstract_func2() 

    

       echo "implement the abstract_func2 in class A/n"

    

    public function iAfunc1(){echo "in iAfunc1";} 

    public function iAfunc2(){echo "in iAfunc2";} 

    public function iBfunc1(){echo "in iBfunc1";} 

    public function iBfunc2(){echo "in iBfunc2";} 

}

Copy after login

5. An interface cannot implement another interface, but can inherit multiple

The code is as follows:

1

2

3

4

5

6

7

8

interface iC extends iA,iB{} 

class F implements iC 

    public function iAfunc1(){echo "in iAfunc1";} 

    public function iAfunc2(){echo "in iAfunc2";} 

    public function iBfunc1(){echo "in iBfunc1";} 

    public function iBfunc2(){echo "in iBfunc2";} 

}

Copy after login

3. Similarities and differences between abstract classes and interfaces

1. Similarities:

(1) Both are abstract classes and cannot be instantiated.

(2) The interface implementation class and the subclasses of abstract class must implement the declared abstract methods.

2. Differences:

(1) interface needs to be implemented, use implements, while abstract class needs to be inherited, use extends.

(2) A class can implement multiple interfaces, but a class can only inherit one abstract class.

(3) Interface emphasizes the implementation of specific functions, while abstract class emphasizes ownership relationships.

(4) Although both interface implementation classes and subclasses of abstract class must implement corresponding abstract methods, the implementation forms are different. Every method in the interface is an abstract method, which is only a declaration (declaration, no method body), and the implementation class must implement it. Subclasses of abstract class can be implemented selectively. This choice has two implications: a) Not all methods in abstract class are abstract. Only those methods with abstract are abstract and subclasses must implement them. For those methods without abstract, the method body must be defined in the abstract class; b) When a subclass of abstract class inherits it, it can directly inherit or override non-abstract methods; and for abstract methods, it can choose to implement or This can be left to its subclasses to implement, but this class must also be declared abstract. Since it is an abstract class, of course it cannot be instantiated.

(5) Abstract class is the intermediary between interface and class. abstract class plays a connecting role in interface and class. On the one hand, abstract class is abstract and can declare abstract methods to standardize the functions that subclasses must implement; on the other hand, it can define default method bodies for direct use or override by subclasses. In addition, it can define its own instance variables for use by subclasses through inheritance.

(6) The abstract keyword cannot be added before the abstract method in the interface. The abstract method is implicit by default, and the final keyword cannot be added to prevent the inheritance of abstract methods. The abstract method in an abstract class must be preceded by abstract to indicate that it is explicitly declared as an abstract method.

(7) Abstract methods in interfaces are public by default and can only be public. They cannot be modified with private or protected modifiers. Abstract methods in abstract classes can be modified with public and protected, but cannot be modified with private.

3. Application occasions of interface

(1) Classes need specific interfaces for coordination, regardless of how they are implemented.

(2) It exists as an identifier that can realize a specific function, or it can be a pure identifier without any interface methods.

(3) It is necessary to treat a group of classes as a single class, and the caller only contacts this group of classes through the interface.

(4) It is necessary to implement multiple specific functions, and these functions may have no connection at all.

4. Application occasions of abstract class

In a word, you can use it when you need both a unified interface and instance variables or default methods. The most common ones are:

(1) Define a set of interfaces, but do not want to force each implementation class to implement all interfaces. You can use abstract class to define a set of method bodies, or even empty method bodies, and then the subclass can choose the methods that it is interested in to cover.

(2) In some cases, pure interfaces alone cannot satisfy the coordination between classes. Variables representing states in the class are also required to distinguish different relationships. The intermediary role of abstract can serve this well.

(3) It specifies a set of mutually coordinated methods, some of which are common, independent of state, and can be shared without the need for subclasses to implement them separately; while other methods require each subclass to implement them according to own specific state to achieve specific functions.

The above is the detailed content of Detailed explanation of php interface and abstract class usage example code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles