This page looks best with JavaScript enabled

Dependency Injection in PHP

 ·  ☕ 1 min read  ·  🤖 Arjit Sharma

When our class need object of other class.

Suppose we have classes : logger(displays a message) UserProfile(Needs to use logger’s log function)

  • Line-11 : We make variable $logger in UserProfile point to object of logger class.
  • Line-15,19,27 : We use $logger to access log function.

3 steps : Initializing Dependency(Line 23),Injecting Dependency(Line 24) and Using Dependency(Line 27).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class logger{
public function log($msg){
    echo "Log : $msg";
  }
}

class UserProfile{
  public $logger;//This variable will store object of logger
  
  public function __construct($logger){
    $this->logger=$logger;//logger variable points to object of logger 
  }  

  public function createUser(){
    $this->logger->log("User Created");//using variable to acces method of logger
  }

  public function deleteUser(){
    $this->logger->log("User Deleted");
  }
}

$logger=new logger();//Initialize dependecy
$profile=new UserProfile($logger);//Inject Dependecy via constructor
$profile->createUser();
$profile->deleteUser();
$profile->logger->log("Hello");//using dependecy
Share on

Arjit Sharma
WRITTEN BY
Arjit Sharma
Yo, I am a CS enthusiast or am I ? Just kidding.


What's on this Page