Home > Backend Development > PHP Tutorial > [PHP Learning] Daily use of inversion of control and dependency injection

[PHP Learning] Daily use of inversion of control and dependency injection

little bottle
Release: 2023-04-05 21:34:02
forward
2351 people have browsed it

The editor of this article will teach you about the use of inversion of control and dependency injection in PHP. If you are interested, come and take a look!

Inversion of control: control is given to your own class

Dependency injection: dependent on another class, I did not manually new it


<?php
/*我自己要用的类*/
class User {
	private $name;
	private $age;
	public function __construct($name,$age){
		$this->name=$name;
		$this->age=$age;
	}
    public static function createResource($conf) {
    	return new self($conf[&#39;name&#39;],$conf[&#39;age&#39;]);
    }
    public function says(){
    	echo $this->name;
    }
}

$conf=array(
	&#39;name&#39;=>&#39;taoshihan&#39;,
	&#39;age&#39;=>10
	);

/*把这个地方放到一个类里,它就是个容器的概念了*/
/*体现了控制反转,所有的操作都是我自己的类里面进行的处理,不需要在调用的时候处理*/
/*这里也体现了依赖注入,就是我不手动去new对象了,我是在下面的方法中获取的对象*/
$user=call_user_func_array(array(&#39;User&#39;, "createResource"), array($conf));

$user->says();
Copy after login

Related courses: PHP video tutorial

The above is the detailed content of [PHP Learning] Daily use of inversion of control and dependency injection. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template