简体   繁体   中英

php: When to use abstract and interface class?

I was wondering how you guys decide when to use abstract or interface class during the application development since they both provide similar functionalities with slightly difference. I appreciate any helps. Thanks.

Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined. Word of caution: use abstract classes and interfaces only if you intend to enforce structure and organization (usually with a team). There's a performance overhead.

I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.

One thing to remember is that any given class can "inherit" (technically implement) many interfaces but only one sub-class (be that abstract or not).

when i'm developing and trying to decide whether to use an interface or an abstract class i usually think about whether classes that will inherit will contain only the same structure (methods, properties etc) but different implementations.

if the implementation of the methods will be different, but i want to ensure sameness from a structural standpoint i use an interface. if the structure and implementation are the same i tend to use abstract classes.

Languages like PHP support multiple interface implementation but not multiple class inheritance, and this is often part of the decision -- will your class support multiple behaviors (interfaces) or will it act as one type of thing (base class)?

There is also the question of how the base functionality is implemented. If you are using an approach like the template method pattern where you have common implementation code for all derived classes, you will want to use an abstract base class.

Here is good article explaining concept of interface and why to use it and how to declare abstract classes in PHP.Though it does not differentiate when to use both concepts.
Understanding and Applying (Interfaces) Polymorphism in PHP

when you bound for certain functionality is required--use interface.but if you want some optional functionality --use abstract class . for example if isi(indian standard institute) makes a standards for computer monitor with functionality(it should have)--Display,power button,contrast setter. if all 3 functionality is compulsory then use interface, which bound monitor manufacturer company to implement all 3 functionality. if any is optional then use abstract class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM