search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the definition and usage of abstract class and interface in php

one,

Abstract classabstract class1. An abstract class refers to a class with the abstract keyword in front of the class and an abstract method (the abstract keyword in front of 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. The abstract keyword must be added in front of the class and cannot be instantiated.

abstract class A  
{  
    /** 抽象类中可以定义变量 */  
    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 A  
{  
    public function abstract_func1()  
    {  
       echo "implement the abstract_func1 in class A/n";  
    }  
    /** 这么写在zend studio 8中会报错*/  
    //abstract protected function abstract_func2();  
}  
class C extends B  
{  
    public function abstract_func2()  
    {  
       echo "implement the abstract_func2 in class A/n";  
    }  
}

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

Class B extends A{};

, then the program will have the following error:

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

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 protected, then the declaration of abstract_func() in B can be public or protected, but cannot be private

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

declare

d 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, interface can declare

constants

variables. However, 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.

interface iA  
{  
    const AVAR=3;  
    public function iAfunc1();  
    public function iAfunc2();  
}  
echo iA:: AVAR;

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

class E implements iA  
{  
    public function iAfunc1(){echo "in iAfunc1";}  
    public function iAfunc2(){echo "in iAfunc2";}  
}
Otherwise, the class must be declared abstract.

abstract class E implements iA{}

4.一个类可以在声明中使用implements关键字来实现某个接口。这么做之后,实现接口的具体过程和继承一个仅包含抽象方法的抽象类是一样的。一个类可以同时继承一个父类和实现任意多个接口。extends子句应该在implements子句之前。PHP只支持继承自一个父类,因此extends关键字后只能跟一个类名。

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";}  
}

5.接口不可以实现另一个接口,但可以继承多个

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";}  
}

三、抽象类和接口的异同

1.相同点:

(1)     两者都是抽象类,都不能实例化。

(2)     interface实现类及abstract class的子类都必须要实现已经声明的抽象方法。

2. 不同点:

(1)     interface需要实现,要用implements,而abstract class需要继承,要用extends。

(2)     一个类可以实现多个interface,但一个类只能继承一个abstract class。

(3)     interface强调特定功能的实现,而abstract class强调所属关系。

(4)     尽管interface实现类及abstract class的子类都必须要实现相应的抽象方法,但实现的形式不同。interface中的每一个方法都是抽象方法,都只是声明的 (declaration, 没有方法体),实现类必须要实现。而abstract class的子类可以有选择地实现。这个选择有两点含义:a) abstract class中并非所有的方法都是抽象的,只有那些冠有abstract的方法才是抽象的,子类必须实现。那些没有abstract的方法,在 abstract class中必须定义方法体;b) abstract class的子类在继承它时,对非抽象方法既可以直接继承,也可以覆盖;而对抽象方法,可以选择实现,也可以留给其子类来实现,但此类必须也声明为抽象类。既是抽象类,当然也不能实例化。

(5)     abstract class是interface与class的中介。abstract class在interface及class中起到了承上启下的作用。一方面,abstract class是抽象的,可以声明抽象方法,以规范子类必须实现的功能;另一方面,它又可以定义缺省的方法体,供子类直接使用或覆盖。另外,它还可以定义自己的实例变量,以供子类通过继承来使用。

(6)     接口中的抽象方法前不用也不能加abstract关键字,默认隐式就是抽象方法,也不能加final关键字来防止抽象方法的继承。而抽象类中抽象方法前则必须加上abstract表示显示声明为抽象方法。

(7)     接口中的抽象方法默认是public的,也只能是public的,不能用private,protected修饰符修饰。而抽象类中的抽象方法则可以用public,protected来修饰,但不能用private。

3. interface的应用场合

(1)     类与类之间需要特定的接口进行协调,而不在乎其如何实现。

(2)     作为能够实现特定功能的标识存在,也可以是什么接口方法都没有的纯粹标识。

(3)     需要将一组类视为单一的类,而调用者只通过接口来与这组类发生联系。

(4)     需要实现特定的多项功能,而这些功能之间可能完全没有任何联系。

4. abstract class的应用场合

一句话,在既需要统一的接口,又需要实例变量或缺省的方法的情况下,就可以使用它。最常见的有:

(1)     定义了一组接口,但又不想强迫每个实现类都必须实现所有的接口。可以用abstract class定义一组方法体,甚至可以是空方法体,然后由子类选择自己所感兴趣的方法来覆盖。

(2)     某些场合下,只靠纯粹的接口不能满足类与类之间的协调,还必需类中表示状态的变量来区别不同的关系。abstract的中介作用可以很好地满足这一点。

(3) Standardizes a set of mutually coordinated methods, some of which are common, state-independent, and can be shared without the need for subclasses to implement them separately; while other methods require individual implementation Subclasses implement specific functions based on their own specific status .

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

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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.