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.


 Live Demo

   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();



Setter Injection

where you inject the object to your class through a setter function.


   class Profile {
      private $language;
      public function setLanguage($language){
         $this->language = $language;
   $profile = new Profile();
   $language = array["Hindi","English","French"];

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.