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

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

little bottle
little bottleforward
2019-04-17 10:07:422268browse

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();

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:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete