Abstract Classes and Interfaces in PHP

Learn via video courses
Topics Covered

Overview

Abstract classes in php and interface in php are important concepts in object-oriented programming (OOP) in PHP. An abstract class serves as a blueprint for other classes and cannot be instantiated on its own. It can contain both concrete and abstract methods. Abstract methods define the method signatures without providing any implementation. Interfaces, on the other hand, define a contract that classes must adhere to. They consist only of method signatures and constants, without any implementation. Classes can implement multiple interfaces but can inherit from only one abstract class. Both abstract classes and interfaces provide a way to enforce structure, standardize behavior, and promote code reusability in PHP applications.

What are Abstract Classes in PHP?

Abstract class in php is a class that cannot be instantiated directly but serves as a blueprint for other classes. It provides a way to define common properties and methods that can be inherited by its subclasses, which are regular classes that extend the abstract class.

An abstract class is declared using the abstract keyword before the class keyword. It can have both regular methods with implementations and abstract methods without any implementation. Abstract methods are declared without a body and are meant to be implemented by the subclasses. They serve as placeholders, ensuring that any class extending the abstract class provides an implementation for those methods.

Abstract class in php are useful when you want to define a common interface or behavior that multiple related classes should have. They provide a level of abstraction, allowing you to define common functionality and enforce certain method implementations in the subclasses. This promotes code reusability and helps in organizing and structuring your codebase.

It's important to note that abstract class in php cannot be instantiated directly, meaning you cannot create objects of the abstract class itself. However, you can create objects of its subclasses, which inherit the properties and methods defined in the abstract class.

Why we use abstract class?

  • Providing a blueprint: Abstract class in php serve as a blueprint or template for other classes. They define common properties and methods that can be inherited by subclasses. This promotes code reuse and reduces duplication, as subclasses can inherit the common functionality from the abstract class.
  • Enforcing structure: Abstract classes allow you to enforce a structure or contract that subclasses must adhere to. By defining abstract methods in the abstract class, you require the subclasses to provide an implementation for those methods. This ensures that certain methods are present in all subclasses, promoting consistency and standardization.
  • Polymorphism: Abstract classes play a crucial role in achieving polymorphism, which is a fundamental principle of object-oriented programming. Polymorphism allows objects of different classes to be treated interchangeably based on a shared abstract class. This facilitates flexible and extensible code design.
  • Abstraction: Abstract classes can be used to represent abstract concepts or entities in your code. They allow you to focus on the essential characteristics and behaviors of an object or a group of objects, while hiding the implementation details. This abstraction promotes a more modular and maintainable codebase.

Example

Explanation

In this example, we have an abstract class Animal that defines a property $name and an abstract method makeSound(). The Dog and Cat classes extend the Animal class and provide their own implementation of the makeSound() method. Run the above code in your editor for a better and clear explanation.

Some Important Facts About Abstract Classes in PHP

  • Abstract classes cannot be instantiated directly: You cannot create objects of an abstract class using the new keyword. They are meant to be extended by subclasses.
  • Abstract classes can have both regular and abstract methods: Abstract methods are declared without a body and are meant to be implemented by the subclasses. Regular methods in an abstract class can have an implementation and can be inherited by subclasses.
  • Subclasses must implement all abstract methods: Any class that extends an abstract class must provide implementations for all the abstract methods defined in the abstract class. Failure to do so will result in a fatal error.
  • Abstract classes can have properties: Abstract classes can define properties, which can be inherited by subclasses. These properties can have default values or be overridden in the subclasses.
  • Abstract classes can be used as type hints: Abstract classes can be used as type hints in method parameters and return types. This allows you to enforce that a passed object or returned value is an instance of a specific abstract class or one of its subclasses.
  • A class can only extend one abstract class: In PHP, a class can only inherit from a single abstract class. Multiple inheritance is not supported. However, a class can implement multiple interfaces while extending an abstract class.

What are Interface in PHP?

Interface in php is a programming construct that defines a contract of methods that a class must implement. It serves as a blueprint for implementing classes, specifying which methods must be present and what parameters they should accept and return. An interface declares the method signatures but does not provide any implementation details.

To declare an interface in PHP, you use the interface keyword. Inside the interface, you define the method signatures without any implementation code. These methods are implicitly assumed to be public and must be implemented with the same visibility in the classes that implement the interface.

A class can implement multiple interfaces by using the implements keyword followed by a comma-separated list of interface names. When a class implements an interface, it must provide implementations for all the methods declared in that interface. Failure to do so will result in a fatal error.

Characteristics of an Interface

Interface in PHP have several key characteristics:

  • Method Signatures: Interfaces define method signatures without providing any implementation details. These method signatures specify the method name, parameters, and return types, but the actual code is left to the implementing classes.
  • Multiple Implementation: A class can implement multiple interfaces, allowing it to define behavior according to the requirements of each interface. This promotes flexibility and code reuse.
  • No Property Declarations: Unlike classes, interfaces cannot define properties. They focus solely on method declarations and constants.
  • No Method Body: Interface methods do not contain any implementation code. They serve as a contract that the implementing classes must fulfill.
  • Full Abstraction: Interfaces are fully abstract, meaning they cannot be instantiated on their own. Instead, they are implemented by classes that provide the actual functionality.
  • Public Accessibility: Interface methods are inherently public. They cannot be declared with private or protected visibility.
  • Constants: Interfaces can include constant declarations, which define values that remain constant across all classes implementing the interface.

Advantages of PHP Interface

Interface in PHP offer several advantages, including:

  • Encourages code reusability: Interfaces provide a contract of methods that classes must implement. This promotes code reusability by allowing multiple classes to implement the same interface, enabling interchangeable usage of objects that adhere to that interface.
  • Supports polymorphism: Interfaces enable polymorphism, which means that objects of different classes implementing the same interface can be treated interchangeably. This allows for flexible and modular code design, as you can work with objects based on their shared behavior rather than their specific class.
  • Enforces method implementation: When a class implements an interface, it must provide implementations for all the methods defined in that interface. This ensures that all classes implementing the interface have the necessary functionality, leading to more robust and reliable code.
  • Enables loose coupling: By programming to interfaces rather than specific classes, you reduce the coupling between different parts of your code. This allows for easier maintenance, testing, and refactoring, as changes in one class or interface won't have cascading effects on other parts of the codebase.
  • Simplifies collaboration: When working in a team, interfaces serve as a common contract that everyone can follow. Team members can work on different classes implementing the same interface simultaneously, knowing that the classes will work together seamlessly.

Example : PHP - Using Interfaces

Let see an example of interface in php:

Explanation

In this example, we have an interface called Vehicle that defines two methods: start() and stop(). The Car class and Motorcycle class both implement the Vehicle interface, meaning they provide an implementation for both methods defined in the interface. Run the above code in your editor for a better and clear explanation.

By implementing the interface, the Car and Motorcycle classes guarantee that they will have the start() and stop() methods available. This allows us to create objects of these classes and call these methods, providing a consistent interface for interacting with different types of vehicles.

PHP - Interface in php vs. Abstract Classes in php

  1. Definitions:
  • Interfaces: Interfaces define a contract by specifying method signatures that implementing classes must adhere to. They cannot have method implementations or properties.
  • Abstract Classes: Abstract classes are partially implemented classes that can contain both method declarations (including abstract methods) and implemented methods. They can also have properties.
  1. Multiple Inheritance:
  • Interfaces: PHP allows implementing multiple interfaces, allowing a class to inherit and implement behavior from multiple sources.
  • Abstract Classes: PHP does not support multiple inheritance for classes. A class can only extend a single abstract class.
  1. Method Implementation:
  • Interfaces: Interfaces do not provide method implementations. Implementing classes must provide the implementation for all methods defined in the interface.
  • Abstract Classes: Abstract classes can have both abstract and concrete methods. Abstract methods have no implementation in the abstract class and must be implemented by the subclass.
  1. Code Reusability:
  • Interfaces: Interfaces are primarily used to achieve code reuse and provide a common contract for multiple classes. They allow unrelated classes to share a common behavior through the interface.
  • Abstract Classes: Abstract classes promote code reuse by providing a base class that can be extended by subclasses. They can include reusable concrete methods that are inherited by subclasses.
  • Abstract classes and interfaces are instrumental in dependency injection and mocking scenarios. By coding to interfaces or abstract classes, you can easily substitute dependencies with alternate implementations, facilitating testing and modularity.

Practical Use Case

  • Database Abstraction: Abstract classes and interfaces are often employed in database abstraction layers to provide a unified interface for accessing different database engines. By defining a common interface, developers can switch between database systems seamlessly without modifying the underlying codebase.
  • Framework Development: PHP frameworks extensively use abstract classes and interfaces to define core components and provide extensibility points. For example, a framework might define an abstract Controller class or an interface for database query builders, allowing developers to create custom controllers or implement their own query builder.
  • Plugin/Module Development: Abstract classes and interfaces are useful when developing plugins or modules for extensible applications. They provide a predefined structure and contract for plugin developers to follow, ensuring compatibility and allowing for easy integration with the host application.
  • API Integration: When integrating with external APIs, abstract classes and interfaces can be used to define a consistent interface for interacting with different API providers. This allows developers to switch between providers effortlessly or create custom implementations based on the defined interface.
  • Testing and Mocking: Abstract classes and interfaces play a vital role in unit testing and mocking. By coding to interfaces or extending abstract classes, developers can easily create mock objects to isolate dependencies and test specific components independently.

Conclusion

  • Abstract classes are partially implemented classes that can have both abstract and concrete methods.
  • They provide a base class that can be extended by subclasses to inherit and customize functionality.
  • Interface in php define a contract by specifying method signatures that implementing classes must adhere to.
  • They cannot have method implementations or properties, focusing solely on the declaration of behavior.
  • Multiple interfaces can be implemented by a class, allowing for polymorphism and loose coupling.