简体   繁体   中英

Polymorphism vs dependency injection in PHP?

What is the difference between polymorphism and dependency injection in PHP? To me they seem like the same thing.

Polymorphism is the provision of a single interface to entities of different types. This means that you define one parent class, ie Person and derive multiple other classes off of it. IE Mailman, Programmer, Dentist. These child classes all have something in common with person, but they implement specialized functions as well.

Dependency Injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. The term was coined by Martin Fowler. An injection is the passing of a dependency (a service) to a dependent object (a client). A database is a good example of this. Let's say our person class above needs to persist some data about itself. Dependency injection would involve passing a database object into the Person class to work with. The Person class doesn't worry about how the database persists its information, it is only concerned with the public api of the database. You could effectively swap out databases and as long as their apis are the same, the Person class would not care. This becomes very handy when you want to unit test your classes and need to remove the dependency on the database. You can use dependency injection to pass in a mock database that always returns dummy information.

Here are two previous stackoverflow questions related to each:

What is polymorphism, what is it for, and how is it used?

What is dependency injection?

Also, check out Martin Fowler's site for more information of this. http://www.martinfowler.com/articles/injection.html

I think dependency injection is much simpler. Its like to inject a class(object) and call a parent method. Similar to a wrapper. Polymorphism uses abstract classes and it let you define non-existance functions.

How I understand it now:

polymorphism + injected object = dependency injection

Polymorphism - is when you create objects that implement the same interface, so all objects have the same base methods.

Dependency injection - you inject object, that can be swapped with other object. But all those object implement the same interface (like in polymorphism).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM