- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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?n
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.
- Related Articles
- What is dependency injection in PHP?
- Dependency Injection in C#
- Explain dependency injection in C#
- How to implement dependency injection using Interface-based injection in C#?
- Difference between IOC and Dependency Injection in Spring.
- Difference between Dependency Injection and Factory Pattern.
- How to implement Dependency Injection using Property in C#?
- What are the different ways to implement dependency injection and their advantages in C#?
- What is SQL Injection?
- What is functional dependency and transitive dependency (DBMS)?
- What is Data Dependency?
- What is functional dependency in DBMS?
- What is Transitive dependency in DBMS?
- What is multivalued dependency in DBMS?
- What is Multivalued Dependency (DBMS)?
- What is SQL injection? How can you prevent it?

Advertisements