
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Dependency Injection in PHP
Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.
There are numerous approaches to inject objects, here are couple generally known −
Constructor Injection
In this approach, we can inject an object through the class constructor.
Example
<?php class Programmer { private $skills; public function __construct($skills){ $this->skills = $skills; } public function totalSkills(){ return count($this->skills); } } $createskills = array("PHP", "JQUERY", "AJAX"); $p = new Programmer($createskills); echo $p->totalSkills(); ?>
Output
3
Setter Injection
where you inject the object to your class through a setter function.
Example
<?php class Profile { private $language; public function setLanguage($language){ $this->language = $language; } } $profile = new Profile(); $language = array["Hindi","English","French"]; $profile->setLanguage($language); ?>
Benefits of Dependency Injection
- Adding a new dependency is as easy as adding a new setter method, which does not interfere with the existing code.
Advertisements