Inversion of Control (Inversion of Control, abbreviated as IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. The most common method is called Dependency Injection (DI).
Changing the implementation of the dependency interface through configuration is also the most basic and core function of dependency injection
Flexibly control the instance scope of dependency implementation, singleton, one per thread, one per request, etc.
Dependent parameters, dependent dependencies, etc. management
The code is more concise and the logic is clearer
Mock is convenient for testing (recommended learning: PHP programming from entry to proficiency)
In general, it is to centrally manage the dependencies between function blocks and classes in the application through a unified framework
A simple For an example of dependency injection
Please look at the following code:
<?php class Container { private $s=array(); function __set($k, $c) { $this->s[$k]=$c; } function __get($k) { return $this->s[$k]($this); } }
With the container class, how can we manage the relationship between A and B? As for dependencies, let’s talk in code:
<?php class A { private $container; public function __construct(Container $container) { $this->container = $container; } public function doSomeThing() { //do something which needs class B $b = $this->container->getB(); //to do } }
Then inject class B into the container class:
$c = new Container(); $c->setB(new B());
You can also pass in an anonymous function so that class B will not be passed in It is instantiated immediately, but the instantiation work is completed only when it is actually called:
$c = new Container(); $c->setB(function (){ return new B(); });
The above is the detailed content of What is the use of php dependency injection?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
