Home Backend Development PHP Tutorial PHP OOP Part-Composition vs Inheritance and Dependency Injection

PHP OOP Part-Composition vs Inheritance and Dependency Injection

Jan 05, 2025 am 12:14 AM

PHP OOP Part-Composition vs Inheritance and Dependency Injection

In this series, I will cover the fundamentals of PHP Object-Oriented Programming (OOP). The content will be organized into sequential parts, each focusing on a specific topic. If you're a beginner or unfamiliar with OOP concepts, this series is designed to guide you step by step. In this part, I will discuss about the Composition vs Inheritance and Dependency Injection in PHP. Let's begin the journey of learning PHP OOP together!

Composition vs Inheritance

We have already learned about the relationship between parent and child classes in object-oriented programming, where we saw that a child class can inherit a parent class and access everything from it. This is known as Inheritance.

On the other hand, Composition refers to assigning a parent class as a property value in the child class, rather than inheriting it. Through this, we can access everything from the parent class. This is known as Composition.

Below are examples illustrating Composition and Inheritance.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");
Copy after login
Copy after login
Copy after login

In the first example, we can see that the ShoLink class inherits the Link class. On the other hand, in the second example, the User class does not inherit the Link class. Instead, it assigns an instance of the Link class to one of its properties. As a result, we can access everything from the Link class in both child classes.

Now, a question might arise: if we can already access everything by using inheritance, why should we use composition? After all, with composition, we need to declare an additional property and set its value via construction. This seems like extra work—so what’s the benefit of using composition?

Well, we know that inheritance makes everything in the parent class accessible in the child class. Consequently, even if we don’t want to use certain methods of the parent class or if some properties or methods of the parent class are not needed in the child class, they still become accessible in the child class if they are public or protected members.

To solve this issue, composition is used. With composition, we can make only the required parts of the parent class accessible in the child class. Let’s clarify this further with another example.

If we look closely at the Link class, we can see that it has a show method. Using this method, we can directly display the link created in the ShoLink class.

However, what if we want the User class to prevent anyone from directly viewing the link created for the user? Instead, we might want to display the user’s link alongside their profile.

This is why, in the User class, instead of inheriting the Link class, we are accessing it through composition. As a result, no one can directly view the user’s link through the User class, but they can directly view the ShoLink class’s link.

Favor Composition over Inheritance

Now we have some understanding of composition and when to use it instead of inheritance to solve certain problems. In OOP, there is a principle called "Favor Composition over Inheritance", which means prioritizing composition over inheritance. In other words, for child classes where it’s not necessary to access everything from the parent class, we should always prefer composition over inheritance.

Now, the question arises: how do we decide when to use composition and when to use inheritance?

In this case, we need to base our decision on two types of relationships:

  1. is a -> relationship. If the relationship is “is a”, we should use inheritance.
  2. has a -> relationship. If the relationship is “has a”, we should use composition.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");
Copy after login
Copy after login
Copy after login

If you look at the example of the ShoLink class above, you'll see that the ShoLink class is inheriting from the Link class. So, if I were to define a relationship between them, the relationship would be ShoLink is a Link because ShoLink is essentially a type of Link.

Code Example

// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}
Copy after login
Copy after login

Now, if we look at the example of the User class above, we can see that the User class is using composition with the Link class. So, if I were to define a relationship between them, the relationship would be User has a Link because a User is not a Link, but a User can have a Link or may possess one.

I hope now you have a clearer understanding of composition and inheritance, including when to use each one and which one to prioritize in different situations.

Dependency Injection

Before understanding dependency injection, we need to first understand what a dependency is. A dependency is when a child class uses the members of another class, either by inheritance or composition. In that case, the parent class becomes the dependency of the child class.

In the example above, we saw that when we use composition instead of inheritance, we need to declare a property in the child class and assign the parent class's instance to that property via the constructor. Therefore, if we want to use the User class, we must instantiate the Link class in its constructor because the User class is dependent on the Link class. In other words, the Link class is a dependency for the User class. The issue here is that the instantiation process of the Link class is tightly coupled within the User class.

The problem is that the instantiation of the Link class is limited and specific to the User class. If we want to pass any other class instead of the Link class from the outside into the User class, we cannot do that because we are explicitly creating the instance of the Link class in the constructor and assigning it to the Link property. This is called a Tightly Coupled Dependency, meaning we cannot change this dependency from outside.

However, if we do not instantiate the Link class ourselves in the constructor and instead leave it to the user, meaning when a user uses our User class, they will pass the Link class dependency into the User class, our problem will be solved.

Let's look at the code example below.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");
Copy after login
Copy after login
Copy after login

In this example, we can see that instead of instantiating the Link class in the constructor of the User class, we are passing the dependency of the Link class into the User class from the outside. This process of passing the dependency into the User class via the user is called Dependency Injection. In other words, we are injecting or pushing the Link class's dependency from the outside. This is known as a Loosely Coupled Dependency, meaning we can easily change this dependency from outside.

Now, if the Link class also has its own dependencies, we can also inject those dependencies into it from the outside via the User class. Then, we can simply inject the instance of the Link class into the User class. As a result, we don’t need to worry about the Link class’s dependencies within the User class, because the user will handle it from the outside.

Let’s look at the code example below.

Code Example

// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}
Copy after login
Copy after login

This way, we can inject as many dependencies as we want from the outside, and it will be much more flexible. That’s all for today; we’ll talk in the next lesson.

You can connect with me on GitHub and Linkedin.

The above is the detailed content of PHP OOP Part-Composition vs Inheritance and Dependency Injection. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles