Introduction
If you are also curious and think too much about Dependency Injection in PHP, we can learn about PHP Dependency Injection in our layman’s language.
In Dependency Injection, both are common words with known meanings. Dependency means something is dependent on another thing and if we complete that dependency with the help of a useful parameter that is called injection.
Dependency Injection in PHP With Example
Now, In PHP Dependency Injection is a software approach where we avoided using hard-coded data in our program. In this approach, one object supplies the dependencies to another object.
Also in Dependency Injection, it can change the dependencies value at runtime and as well as compile-time of the execution.
Check the below example to better understand the Dependency Injection,
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php class Programmer { private $names; public function __construct($names){ $this->names = $names; } public function totalNames(){ return count($this->names); } } $createnames = array("John", "MAX", "Mark"); $p = new Programmer($createnames); echo $p->totalNames(); ?> |
Output: 3
Code Explanation
- First, we create a class named Programmer where we create a private variable and one of the parameterized constructor functions to take the values when the object is created.
- Now we create a function that counts the total values which we pass at the time of object creation.
- At last, we create an array with some values.
- Then we create an object of the class and set the array variable as an argument.
- Now we call the function which gets the count of an array of elements.
The above example is also called Constructor Injection.
Some Major Benefits of Dependency Injection
- Dependency injection is used when we want to inject dependencies at runtime and compile time.
- Adding dependencies is as easy as a setter method that does not interfere with existing code.
- By using Dependency Injection we can reduce hard code values on our program.
Conclusion
In this article, we discuss Dependency Injection with an example. Also, I provide a complete explanation of the given example step by step.
Here you can check the layman’s meaning of Dependency Injection and the definition according to PHP programming concepts.
To know more about PHP OOP you can check the official guide PHP: Classes and Objects – Manual.
Happy Coding..!