


PHP OOP Part-Composition vs Inheritance and Dependency Injection
Jan 05, 2025 am 12:14 AMIn 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");
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:
- is a -> relationship. If the relationship is “is a”, we should use inheritance.
- 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");
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 }
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");
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 }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
