Dependency Injection
Last updated
What is Dependency Injection?
Dependency injection is a design pattern used mainly for managing class dependencies. Here, instead of a class being responsible for creating its dependencies on its own, an injector (the "client") passes the requirements to the class (the "service"), centralizing control and encouraging code to follow the single responsibility principle. As a simple example, consider a situation where class B needs to utilize class A's methods. Instead of creating an object of class A within B, with dependency injection, we pass an instance of class A to B.
class A {
function display(){
echo 'Hello, PHP dependency injection!';
}
}
class B {
private $a;
public function __construct(A $classAInstance) {
$this->a = $classAInstance;
}
public function callDisplayOwn() {
$this->a->display();
}
}
$instanceA = new A();
$instanceB = new B($instanceA);
$instanceB->callDisplayOwn(); // Outputs: "Hello, PHP dependency injection!"
Free resources to learn Dependency Injection
More in stage 12: PHP-FIG
Dependency Injection: common questions
Can I learn Dependency Injection in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Dependency Injection in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Dependency Injection tutorial for beginners?
It is lesson 89 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.