PHP Interfaces & Abstract Classes. When to use which.
![]()
PHP offers quite a range of OOP features to impower your logic and problem solving abilities. Two of these features which I find so useful are Interfaces and Abstract Classes.
Actually, when look at, they both sound the same at first. Both have methods signatures with no implementations, and both are used in the definition of other classes. But, wait. That’s not the full picture!
Let’s look at each one of them and it’s features, first. Get to know each one better and then decide which one is good for what.
PHP Interfaces
In the words of php.com, interfaces are defined as:
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented. Interfaces share a namespace with classes and traits, so they may not use the same name.
Now, what does that mean? Let’s look at an interface declaration:
The interface declaration provides only the required methods signatures. It doesn’t provide any implementations. The class defined using this interface MUST contain all the methods defined in this interface (i.e.: doThis() and doThat()), and will have to take care of these methods implementations. So, let’s use this interface to define a new class. We do this using the implements keyword.
As you can see, the logic is left for the class to implement. Interfaces provide blue prints of how the classes must be defined.
Worth noting here are following:
- all methods signature definition in interface are public.
- the class implementation of the methods must match not only the methods but their arguments types. Otherwise, this will result in a Fatal error!
- that interfaces cannot be used to instantiate objects like we do with classes.
So the following will throw a fatal error:
Implementing an interface in class definition doesn’t mean that we r stuck with only those methods specified by the interface. The interface tells us the minimum methods required for the class, and we can add the rest, methods and properties and even constants, that we feel needed in our class. So let’s look again at our earlier example and add some more methods and properties.
Interface Extension:
Let’s look at the following scenario.
In the above interface example we wrote, we want more methods to be included in addition to the 2 we already have in MyInterface. Adding them in MyInterface definition means you will have to through all your code and change the definitions of the classes implementing this interface, or else, you code will crash!
In stead of modifying MyInterface, we can extend it to a new interface, adding the new methods there. This leaves all classes defined earlier unchanged and allows us to define new interface and new classes with new methods. Just like the below:
The class implementing the new interface will have to implement all methods defined by all interfaces extended.
Another way to do the above is to define an interface with only the new methods and without extending the old interface. Then implement MyInterface and MyNewInterface together. Like this.
Interfaces with Constants:
Interfaces can include constants which are accessed statically and for PHP versions prior to 8.1.0, constants cannot be overridden in class definitions.
Interfaces as arguments types:
Interfaces can be also used as arguments typing in functions and methods. It is a way of saying that the required argument must have this minimum requirement. Let’s look at the example below:
Any object to be passed as an argument to myFunction must be an instance of a class implementing MyInterface, and since $myObj is of class MyClass which implements MyInterface, it is acceptable. This way, the function knows what minimum methods it should expect in the passed object.
Interfaces Summary:
- Interfaces are blueprints. They cannot be instantiated. They provide the minimum required methods for classes definitions and functions argument typing.
- They contain only the methods signatures. Methods implementations are left for classes.
- All their methods are public and they can’t contain properties.
- Classes must include all methods defined by the interfaces they implement, including interfaces extended by the implemented interfaces.
PHP Abstract Classes
Abstract classes and abstract methods are used when u want to define some required methods signatures and leave the implementation of these methods for developers to do.
Abstract classes are used to define the elements of a class and cannot be instantiated. Classes extending abstract classes will have all elements defined by the extended abstract classes and just like interfaces, all abstract methods in the abstract classes extended must be implemented in the extending class.
Let’s look at an example.
As you can see, all methods and properties declared in the abstract class are inherited by the extending class. Also, the extending class must implement all abstract methods declared in the extended abstract class.
Please, note the following:
- Any class containing abstract methods must be declared as an abstract class.
- Abstract methods define the methods signatures and cannot define the implementation.
- Inherited methods defined in abstract classes are overridable in the extending classes unless declared final.
- abstract classes can extend other abstract classes resulting in extending classes inheriting defined methods and properties and, just like in interfaces, having to implement all abstract methods of all extended abstract classes.
- Classes can extend only one class, (i.e. can inherit from only one class through extends keyword.) This is unlike the allowed multiple implementations of interfaces.
That’s pretty much it.
Abstract Classes Summary:
- Abstract classes act like templates for new classes definitions where you can predefine methods, properties and constants, allowing overriding methods and enforcing the implementation of some methods by users.
- Classes defining abstract methods must be defined as abstract classes.
- All abstract methods in an extended (inherited) class must be implemented by the extending (inheriting) class.
- Abstract classes can contain members of different modifiers (public, private and protected), unlike interfaces where only public members are allowed.
- Abstract classes can have static members as long as they are complete (i.e. constants or implemented methods.)
So, when to use which?
Now that we have looked at both, interfaces and abstract classes, which one is used when? or when to use which?
Interfaces:
As a standard, since interfaces provide blueprints or a protocol for the minimum expected methods in a class to be acceptable by a function or a process, leave the implementation of these methods for the users, it is best used when you need to accept a class as an argument in a function or a method and you don’t really care which class it is as long as it contains the necessary methods required by the calling function or method.
They are not good when you need a class to inherit methods and properties as interfaces can have neither the properties or the methods implementations.
Consider it like an agreement between the calling function or method and the called class to have certain methods implement. Example below:
Abstract Classes:
Abstract classes are a good practice of code recyclability as they provide a kind of a complete class definition which can be used to derive a new class based on certain members, leaving developers the option of overriding and/or implementing certain abstract methods. In other words, this provide a ready made template you can use to build classes through inheritance.
So, use abstract classes when you want to define a class based on another, with already implemented logic, and leave more flexibility for developers to add their own logic but keeping up with the minimum class functionality.
Example of such would be:
Abstracts can be used in the same manner as interfaces if you include only public abstract methods and extend them in class definitions instead if implementing them as in the case of interfaces. This will give you the same effect of using a protocol or a blueprint for the minimum methods required. But, this is not an advised practice unless implied by code requirements and you know what you are doing.
I hope this was informative an clear enough. If you have comments, additional information you want to share, or a question you want to ask, please feel free to add it in the comments below.
Абстрактные классы в ООП на PHP
Пусть у вас есть класс User , а от него наследуют классы Employee и Student .
При этом предполагается, что вы будете создавать объекты классов Employee и Student , но объекты класса User — не будете, так как этот класс используется только для группировки общих свойств и методов своих наследников.
В этом случае можно принудительно запретить создавать объекты класса User , чтобы вы или другой программист где-нибудь их случайно не создали.
Для этого существуют так называемые классы. Абстрактные классы представляют собой классы, предназначенные для наследования от них. При этом объекты таких классов нельзя создать.
Для того, чтобы объявить класс абстрактным, нужно при его объявлении написать ключевое слово abstract :
Итак, давайте напишем реализацию абстрактного класса User . Пусть у него будет приватное свойство name , а также геттеры и сеттеры для него:
Попытка создать объект класса User вызовет ошибку:
А вот унаследовать от нашего класса будет можно. Сделаем класс Employee , который будет наследовать от нашего абстрактного класса User :
Создадим объект класса Employee — все будет работать:
Аналогично можно создать объект класса Student , наследующий от User :
Самостоятельно, не подсматривая в мой код, реализуйте такой же абстрактный класс User , а также классы Employee и Student , наследующие от него.
Абстрактные методы
Абстрактные классы также могут содержать абстрактные методы. Такие методы не должны иметь реализации, а нужны для того, чтобы указать, что такие методы должны быть у потомков. А собственно реализация таких методов — уже задача потомков.
Для того, чтобы объявить метод абстрактным, при его объявлении следует написать ключевое слово abstract .
Давайте попробуем на практике. Пусть предполагается, что все потомки класса User должны иметь метод increaseRevenue ( увеличить доход ).
Этот метод должен брать текущий доход пользователя и увеличивать его на некоторую величину, переданную параметром.
Сам класс User не знает, какой именно доход будет получать наследник — ведь у работника это зарплата, а у студента — стипендия. Поэтому каждый потомок будет реализовывать этот метод по-своему.
Фишка тут в том, что абстрактный метод класса User заставляет программиста реализовывать этот метод в потомках, иначе PHP выдаст ошибку. Таким образом вы, или другой программист, работающий с вашим кодом, никак не сможете забыть реализовать нужный метод в потомке.
Итак, давайте попробуем на практике. Добавим абстрактный метод increaseRevenue в класс User :
Пусть наш класс Employee пока останется без изменений. В этом случае, даже если не создавать объект класса Employee , а просто запустить код, в котором определяются наши классы, — PHP выдаст ошибку.
Давайте теперь напишем реализацию метода increaseRevenue в классе Employee :
Проверим работу нашего класса:
Реализуем метод increaseRevenue и в классе Student . Только теперь наш метод будет увеличивать уже стипендию:
Добавьте в ваш класс User такой же абстрактный метод increaseRevenue . Напишите реализацию этого метода в классах Employee и Student .
Добавьте также в ваш класс User абстрактный метод decreaseRevenue ( уменьшить зарплату ). Напишите реализацию этого метода в классах Employee и Student .
Некоторые замечания
При наследовании от абстрактного класса, все методы, помеченные абстрактными в родительском классе, должны быть определены в дочернем классе.
При этом область видимости этих методов должна совпадать или быть менее строгой. Что значит менее строгой: например, если абстрактный метод объявлен как protected , то реализация этого метода должна быть protected или public , но не private .
Объявления методов также должны совпадать: количество обязательных параметром должно быть одинаковым. Однако класс-потомок может добавлять необязательные параметры, которые не были указаны при объявлении метода в родителе.
Практика
Пусть нам необходимо работать с геометрическими фигурами, например, с квадратами, прямоугольниками, треугольниками и так далее. Пусть каждая фигура будет описываться своим классом, при этом мы хотим сделать так, чтобы каждый класс имел метод для вычисления площади и метод для вычисления периметра фигуры.
Давайте сделаем для этого абстрактный класс Figure с двумя абстрактными методами getSquare и getPerimeter .
Почему класс Figure абстрактный: потому что он не описывает реально существующую геометрическую фигуру и, соответственно, объект этого класса мы не будем создавать.
Почему методы getSquare и getPerimeter абстрактные: потому что каждая фигура имеет свой алгоритм вычисления площади и периметра и, соответственно, класс Figure не может написать реализацию этих методов.
Зачем нам вообще нужен класс Figure : чтобы наследовать от него и таким образом заставить всех наследников реализовать указанные методы.
Итак, напишем реализацию класса Figure :
Пусть теперь мы хотим создать класс Quadrate для описания геометрической фигуры квадрат. Как известно, у квадрата все стороны равны, поэтому для описания квадрата нам нужно задать только его ширину.
Давайте для этого сделаем приватное свойство $a , значение которого будет задаваться в конструкторе класса:
Давайте теперь унаследуем наш класс Quadrate от класса Figure :
Сейчас наша реализация класса Quadrate не рабочая, так как мы не написали реализацию абстрактных методов родителя.
Давайте сделаем это:
Давайте создадим квадрат со стороной 2 и найдем его площадь и периметр:
Сделайте аналогичный класс Rectangle ( прямоугольник ), у которого будет два приватных свойства: $a для ширины и $b для длины. Данный класс также должен наследовать от класса Figure и реализовывать его методы.
Усложним
Сейчас все методы класса Figure — абстрактные. Это, конечно же, не обязательно. Пусть наш класс имеет еще и метод getRatio , который будет находить отношение площади к периметру (то есть одно делить на второе).
Этот метод уже будет не абстрактный, а иметь реализацию, и все потомки смогут воспользоваться этим методом.
Почему мы можем написать реализацию этого метода прямо в классе Figure : потому что этот метод будет одинаковым для всех потомков.
Итак, добавим наш метод:
Обратите внимание на следующее: хотя методы getSquare и getPerimeter абстрактные и не имеют реализации, мы их все равно можем использовать в своем методе getRatio , хотя реализация этих методов появится только в потомках.
Применим наш метод:
Добавьте в класс Figure метод getSquarePerimeterSum , который будет находить сумму площади и периметра.
Зачем нужны абстрактные классы (PHP)?

У разных языков по разному. Например в Java можно реализовывать кучу интерфейсов, но нельзя реализовать множественное наследование не больше 3-ех наследников и с помощью интерфейсов решают это.
Интерфейс нужен обычно, когда описывается только интерфейс (тавтология). Например, один класс хочет дать другому возможность доступа к некоторым своим методам, но не хочет себя «раскрывать». Поэтому он просто реализует интерфейс.
Абстрактный класс нужен, когда нужно семейство классов, у которых есть много общего. Конечно, можно применить и интерфейс, но тогда нужно будет писать много идентичного кода.
Пример: Абстрактный класс заведомо не будет запрошен как объект. К примеру абстрактный класс — Транспорт: Но все его наследники будут Автомобилем, краном, лодкой, самолет и т.д. Например вы заведомо знаете, что весь транспорт будет двигаться. И вы объявляете абстрактный метод(движение) в абстрактном классе, который нужен будет 100% всем наследникам т.е. без движения это уже не транспорт и новый наследник обязан будет реализовать это. В самом же абстрактном классе, есть другие поля и свойства, которые будут унаследованы. Ну например мощность двигателя(очень грубо), или то что их роднит.
- Вконтакте

Анна Б: вы стучитесь в методы наследников не через абстрактный класс, а напрямую.
Вы в своем приложении создаете новый объект и используете его методы.
например
$airplains = new Airplains ; // Тут создается объект
$airpalins->getEngine(); // Тут получается свойство объекта, которое он наследовал от абстрактного класса, либо какое-то свое свойство. В моем примере это двигатель.
$airplains->move(); // тут использование метода движение, которое было унаследовано у абстрактного, но сама реализация этой функции в классе Самолет.
Самолет и Машина двигаются по разному и это «описание» пишется в методе мув, !ДЛЯ КАЖДОГО СВОЕ. Но названия метода у них одинаковые. Это позволяет передавать разные объекты и не переживать за то, что они все будут исправно работать, если вы передадите самолет он летит, если машина то она поедет. Каждый класс знает, что ему делать. Если вы не реализуете абстрактный метод в других классах, классы будут кидать ошибку и требовать от вас их реализации.
ваш код $this->move() // взять текущий объект и использовать метод мув. Если такой метод есть, а он у вас есть. То все будет окей.
Если вы делаете это не через абстрактный класс, а просто через класс. Это будет переопределение метода. На практике это выходит так: у вас есть описание как двигается самолет, а потом вы вызываете машину и машина начинает использовать тоже самое, что и самолет в итоге машина летит, а не едет.
What is an Abstract Class in PHP?
In this comprehensive article, we will go deep into the realm of PHP abstract classes. This article will offer you with a full overview of how to utilize abstract classes in your PHP development projects, from comprehending the principles to examining the syntax and implementation. This article will provide you with the knowledge and abilities to successfully work with abstract classes in your code, whether you are a newbie or an experienced developer.
An abstract class contains the declaration of methods but not their definition. It only contains their names. It is the responsibility of the child class to define these methods.
What is an abstract method?
An abstract method is a method of an abstract class that is declared using abstract keywords and does not contain the body. It is defined by the child’s class.
- abstract keyword is used to declare an abstract class or method.
- An abstract class must contains at least one abstract method. However, it can also contains non-abstract methods as well.
Syntax
What are the rules of abstract class in PHP?
- An abstract class must contains at least one abstract method. However, it can contains non-abstract methods as well.
- When a child called inherit the abstract parent class, it must defines the abstract methods of parent class with the same name.
- While defining the asbtract methods in the child class, it should be defined with less restricted access modifier. For instance, if the parent class contains the abstract method having protected access modifier. So, when the child class defines this method, it should keep its access modifier as either protected or public. It cannot set it to private, becasue it is more restricted than the protected.
- The child class defining the abstract method must pass the equal number of arguments as specified in the declration in the parent asbtract class. However, the child class can have optional/extra arguments other than those required.
Example of Abstract class in PHP
Explanation of the above example
- In the above example, we create an abstract class Bike that contains an abstract method introduction.
- We create two child classes Honda and Suzuki that extends the abstract class and defines the introduction method.
- We create the objects of these classes and call the introduction method using their objects. The introduction method works according to the implementation given by its corresponding class.
Example of abstract class with extra arguments in method overriding
Explanation of the above example
- The basic logic of the above example is like the previous example. However, we pass extra argument to the function in the introduction method of suzuki class.
- As we have define the rule earlier in this tutorial, the access modifier of the child class while implementing the abstract method of the parent class must be less than as specified in the parent class for the declaration of this method. So, both the child classes uses public access modifier to define the introduction method.
- Try to define the function with private access modifier, it will produce an error.
Note: The abstract class does not contain any constructor method. So, we cannot create the instance of an abstract class.