r/PHPhelp • • Nov 17 '22

Solved PHP Abstract Classes, PHP Interfaces

I read about it online and still can't understand what these two is about. How does it work and when do you use these two? Can someone give example and explain these to me in simple words? Thanks!

8 Upvotes

9 comments sorted by

View all comments

1

u/ZippyTheWonderSnail Nov 17 '22

An abstract class is like an interface with the ability to add functional code. So a class which extends an abstract class may have to implement functions, and may also inherit functions and properties.

https://www.php.net/manual/en/language.oop5.abstract.php

8

u/CyberJack77 Nov 17 '22

There are way more differences between interfaces and abstract classes, so to say an abstract class is like an interface is simply selling it short.

An interface can be seen as a blueprint that describes the public API. In other words, it describes all public methods that should be implemented when using the interface. The interface cannot contain protected and private methods and cannot contain properties or constants. A class can implement multiple interfaces, and each of the described public methods must be implemented in the class.

An abstract class is a class that cannot be instantiated by itself, and to use it, it must be extended. An abstract class can contain public, protected and private methods, abstract methods, properties and constants. The abstract class can extend another class and can also implement interfaces. A class can extend the abstract class and the "abstract" methods need to be implemented in the class itself. Any missing methods from applied interfaces must also be implemented in the class that extends the abstract class.

Since PHP does not support multiple inheritance, a class can only extend one other (abstract) class. This can cause some problems If you need methods from multiple (abstract) classes and things can become messy really quickly. There is a whole composition over inheritance discussion, but I don't think that is needed to explain the differences between an interface and an abstract class.