Dependency Injection

Learn about the tight coupling problem and how to solve it using dependency injection.

One of the less understood subjects for fresh PHP programmers is that of dependency injection. This lesson will explain the subject in the simplest way possible by first explaining the problem and then showing how to solve it.

The problem: Tight coupling between classes

When class A cannot do its job without class B, we say that class A is dependent on class B. In order to perform this dependency, many programmers create the object from class B in the constructor of class A.

For example, say we have the classes Car and HumanDriver. The Car class is dependent on the HumanDriver class, so we might be tempted to create the object from the HumanDriver class in the constructor of the Car class.

Get hands-on with 1200+ tech skills courses.