search
HomeBackend DevelopmentPHP TutorialAbstract classes and interfaces in PHP

Abstract classes and interfaces in PHP

Dec 02, 2017 pm 01:39 PM
phpabstractinterface

In actual PHP development we will often use PHPabstract classes and interfaces. Today we will talk about them in detail What are the abstract classes and interfaces of PHP talking about.

1. Abstract class abstract class

1. An abstract class refers to a class with the abstract keyword added before class and an abstract method (the 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 the 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.

Abstract class A

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 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 interface1 . 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. Private and protected methods cannot be declared. Method bodies cannot be defined, and instance variables cannot be declared. However, interface can declare constant variables. But placing constant variables in interface violates the purpose of its existence as an interface, and also confuses the different values ​​​​of interface 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. 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 come before the implements clause. PHP only supports inheritance from one parent class, so the extends keyword can only be followed by a class name.

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. An interface cannot implement another interface, but it can inherit multiple

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

3. Similarities and differences between abstract classes and interfaces1. Similarities :

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

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

2. Differences:

(1) Interface needs to be implemented, using implements, while abstract class needs to be inherited, using 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 the ownership relationship.

(4) Although both interface implementation classes and abstract class subclasses must implement corresponding abstract methods, the implementation forms are different. Every method in interface is an abstract method, which is only declared (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 must be implemented by subclasses. For those methods without abstract, the method body must be defined in abstract class; b) When a subclass of abstract class inherits it, it can directly inherit or override non-abstract methods; for abstract methods, it can choose to implement or Implementation can be left to its subclasses, 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. In an abstract class, abstract must be added before the abstract method 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 let subclasses choose the methods they are 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 all about abstract classes and interfaces in PHP. I hope it will be helpful to everyone.

Related recommendations:

php Detailed explanation of the implementation method of abstract class

php Detailed explanation of the difference between abstract classes and interfaces and selection of examples

phpDetailed explanation of abstract class feature examples

The above is the detailed content of Abstract classes and interfaces 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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.