R
R
Ruslan Ruslanov2019-09-10 09:19:51
PHP
Ruslan Ruslanov, 2019-09-10 09:19:51

Why are abstract classes and interfaces needed in php?

I read a lot of questions and articles, but I will repeat this question, which was asked thousands, and perhaps tens and hundreds of thousands of times before me, again:
Why do we need abstract classes and interfaces? And in php too.
I understand this: an abstract class allows you to declare methods for child classes, also not to define parent methods in the heir class, and that in fact it differs from a regular class in that there is an "abstract" prefix in the name of some methods and the class name and that you cannot create his copy. Question: why is it needed at all?
As I understand it (the abstract class) is purely decorative, it is needed to limit the actions of the developer, the convenience of development, and in general it is just "sugar".
The same topic with interfaces. Why are they needed if then their methods and properties will be overridden? And if not, then what is worse than inheritance from a regular parent class, where you can also define properties and methods, but omit the implementation?
There are other traits, but they are more or less clear. In order not to produce parent classes and not to be re-inherited from them each time, creating huge chains of inheritance, traits are used in which the method that is in the parent class is defined, and then the trait is connected to the heir class, overrides the parent method and there is no extra fuss.
So why do we need abstract classes and interfaces?

Answer the question

In order to leave comments, you need to log in

9 answer(s)
H
hack504, 2019-09-10
@dasauser

Yes, they are purely declarative. But in design and development, the development team is very much needed. For example, we have a certain entity Tariff, from which specific implementations are generated (Promotional, limit, unlimited, special - not the essence) - something can unite / separate them. Therefore, when I write a class that somehow interacts with the Tariff with a certain attribute, then I can explicitly indicate this by creating a special Interface and request an instance of the class of this particular interface, and not the parent class:
Next, implement this interface on all descendants of the Tariff class where necessary, and do not worry that after some time another developer will create a new implementation of the tariff and bugs will fall from your code

D
Demian Smith, 2019-09-10
@search

An interface is a contract that implements a class, and users of the class know how to use the class. This is an alternative to multiple inheritance. For example, you have two collection types: a binary tree and a graph. These are quite different data structures. But each of the collections can implement the Iterator interface, in which case the interpreter will know how to iterate over the collection in the foreach loop.
Abstract classes are mainly used if some part of the code can be described in the parent class, but in order for this part to make sense, specifics are needed: to supplement the overall picture with details in the form of methods or fields. If you take a closer look at abstract classes in modern frameworks, you'll see that an abstract class by itself doesn't make sense. For example, if you create an object of such a class with the new operator, then this object will still lack something, and it is this something that the child classes add.

N
Ninazu, 2019-09-10
@Ninazu

1. An abstract class cannot be created, only an object can be created from an inherited class
2. An abstract class can contain an implementation, unlike an interface
3. An abstract class can contain abstract methods that will need to be implemented in child classes
4. You can implement several interfaces at once, and inherit from only one class.
5. Traits combine very well with interfaces
You will realize why this is needed during use)) Read also about SOLID, and try to implement these principles without abstractions and interfaces)
PS Homework
There are three classes. Square , Rectangle , Circle . And classBox . We add arbitrary sets of shapes to the box, and we need to calculate the area of ​​all the shapes in the box.

N
Northern Lights, 2019-09-10
@php666

so clearer?

интерфейс гуманоид (декларация человекоподобного существа и декларация его базовых методов - идти, бежать, думать, размножаться)

-> абстрактный класс человек (имеет реализацию задекларированных в интерфейсе методов, имеет общую реализацию)
 -->  конкретный класс человек мужчина (частности реализации)
 -->  конкретный класс человек женщина (частности реализации)

-> абстрактный класс инопланетянин (имеет реализацию задекларированных в интерфейсе методов, имеет общую реализацию)
 -->  конкретный класс инопланетянин мужчина (частности реализации)
 -->  конкретный класс инопланетянин женщина (частности реализации)

If you were a creator, you would need exactly this structure to create a humanoid-shaped creature (two arms, two legs, head, upright, two eyes - this is an INTERFACE - a declaration that all classes will implement this convention).
A person cannot be inherited from an alien, as well as vice versa - these are DIFFERENT forms of life. One is built on the carbon form (man), the other, say, on the basis of methanogens. But what they have in common is the HUMANOID interface, created "in the image and likeness" (c).
For these two different types, we create base ABSTRACT classes (because neither human nor alien, from our point of view, as a creator, can be of an indefinite gender). In abstract classes, we implement methods that are declared in our interface. We fill abstract classes with properties and all the methods inherent in both sexes of our creations, because there is a lot in common between a man and a woman in the structure.
Concrete classes are already the final sexes of two different types of lifeforms.
PS I am a god, worship me!

M
Maxim, 2019-09-10
@Tomio

When working with OOP, you need to clearly drive it into your head that in front of you are not classes, but objects . And you need to develop the architecture of the application, too, with an emphasis on this concept.
All of the above are interfaces for interaction with the internal mechanisms of devices. Interfaces introduce some kind of abstraction. You don't know how the device works inside. You can have one interface, but the implementation of the internal functionality is completely different. That is, for example, you have a toggle switch on the dashboard of a car that regulates the temperature of the air conditioner. But you don't know what's going on inside when you spin it.
Let's move on to programming. This very toggle switch is an interface element, it launches the public setTemperature method . That's all you need to know about him.
That is, in summary, interfaces are a declared abstract layer of an application with a limited set of public methods available.interaction with this application. Your application can and will contain private methods, because if you use OOP, encapsulation must be mandatory in order to hide mechanisms unnecessary for the user in a black box. It is important for the user to understand that by turning the toggle switch, the temperature will change - that's all. And how it will be changed is up to the programmer.
An abstract class is essentially the same interface, but only in it you can predefine some methods in advance and use them in the inherited class. Abstract methods are needed so that they are necessarily implemented in the heir class, because without them the heir class will not fully work.
For example, there is an abstract class that works with the selection and transfer of data from one database to another. And all the methods in it are already implemented, except for one abstract one - getQuery , - a method that returns a string with an SQL query. After all, the request can be different and you never know what conditions will be in it. This is some kind of abstract request that is unknown. And just under this action it is very convenient to have an abstract method.

A
Arthur K., 2019-09-22
@amark

Now I'm reading this old article , and I remembered your question.
The article writes about the principles of good software architecture, and, among other things, explains why interfaces / abstract classes, etc. are needed. Recommend.

R
RabraBabr, 2019-09-10
@RabraBabr

How is this why? What sugar? The base abstract class defines an interface. And then several different child classes define different implementations for different types of objects. But thanks to the base abstract class, for example, you can create these different objects with one factory or use them in other patterns, and the classes of these patterns can work with these objects through the interface, in principle, knowing nothing about these objects (about their implementation).
Once you take the first step, don't hesitate to take the second. Read about SOLID and GRASP about design patterns. When you reach a new level of abstract thinking. In the head there will be (enlightenment) an understanding of OOP (and not this primitive mantra of three terms - encapsulation, inheritance, polymorphism). Large commercial projects are all made entirely on abstractions. Everything is very abstract.

V
vgbege, 2019-09-10
@vgbege

I would also advise starting not from the end (why are there abstract classes and interfaces in a high-level language), but from the beginning - how programming developed from assembler / basic with a bunch of variables and jmp / goto to the structural paradigm, and then to OOP and why they needed it there abstract classes and interfaces. moreover, I'm not a specialist in php and I don't know how these same classes and interfaces are implemented in this weakly typed language :)
a direct answer to the question "why" - to implement the composition of objects. Google dependency injection, inheritance vs composition. in general, the question of why is no longer worth it, now these are time-tested basics that you just need to know.
if on the fingers - in strongly typed languages, a variable of type IMyInterface can store instances of classes that implement IMyInterface. a variable of type MyAbstractClass can store instances of classes derived from MyAbstractClass.
for example, from the abstract Logger class with the log(s: string) method, we can generate real classes Console Logger, EmailLogger, DBLogger, SMSLogger, etc., and then throw a console email in the developer environment, and in the combat email, etc. .
I hope I answered a direct question and didn't stress too much with reference to basic knowledge :D

T
terminator-light, 2019-09-11
@terminator-light

If you already have a class that inherits another class, and some library requires you to pass an object that belongs to some other type, and at the same time you cannot inherit from another class, because you have already inherited from one, because there is no multiple inheritance in your language (for example, take Java):

class Coffee{
   
}

class Cappuccino extends Coffee{

}

//метод в библиотеке
public void serialize(Serializable s){

}

Lib was designed in such a way that its method would take an interface type, not a class type. And so you just need to implement this interface:
class Cappuccino extends Coffee implements Serializable{

}

and the abstract class, I think, is a tool for emphasizing the intentions of the developer. To make it clear that this class is not intended for the same use as a normal class, for instantiation.
If the interface can show some behavior like:
Serializable, Parcelable, Runnable, Callable, Comparable, Clonable
etc., then the abstract class shows basicity, abstractness, i.e. relation is-a Take, abs. class DataSourceand its descendants RemoteDataSource, LocalDataSourceand MemoryCacheDataSource, i.e. we make it clear that you can't just instantiate a DataSource.
Based on the foregoing, we can distinguish:
1. the interface introduces multiple type inheritance into the language
2. the interface and the abstract class serve a declarative purpose

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question