What Is Dependency Injection in PHP and How You Can Use It to Write Better Code

Tomasz Dobrowolski
3 min readMar 5, 2022
Person coding with headphones on
Photo by Jefferson Santos on Unsplash

If you are familiar with PHP, you have probably come across the term Dependency Injection.

While it sounds complex, it’s not as scary as it sounds on the surface. And if used correctly, it can transform your code to be cleaner and easier to work with.

Here’s all you need to know about dependency injection:

What is dependency injection?

To break it down: Dependency Injection is the process of passing objects into another object.

The object we are creating has a dependency on another object to do its job.

So how do we use dependency injection? By passing in the object (dependency) as a parameter in a constructor or a regular function.

The point of dependency injection is to handle the creation of an object outside of the class. The object is passed in as a parameter, rather than doing the instantiation inside the class.

How do you use dependency injection in PHP?

Let's say we have an Order class.

The idea of this class is to create an order. But for an order to be created, we need to check if a payment has been made.

So, we need to create our Payment object to call the checkIfPaymentSuccessful method.

Without Dependency Injection:

In this example, we want to deal with the Payment object, therefore we instantiate it in the constructor:

class Order
private $payment;

//Payment Object is initialised inside the constructor
public function __construct($paymentId){
$this->payment = new Payment($paymentId);
public function checkIfOrderCanBeMade(): object
$paymentSuccessful = $this->payment->checkIfPaymentSuccessful();
if ($paymentSuccessful){
return $this->createOrder();
else {
return $this->failedPaymentOrder();

As you can see, the object Payment is created within the class and we have to pass in the properties which the Payment class…

Tomasz Dobrowolski

I break down Software Engineering and Tech concepts | Backend Engineer 🐘