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

 Live Demo

<?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.

Updated on: 29-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements