<?php /* 无Di容器的写法 class example { private $_db; function getList(){ $this->_db->query("......");//这里具体sql语句就省略不写了 } //从外部注入db连接 function setDb($connection){ $this->_db = $connection; } } //调用 $example = new example(); $example->setDb(Factory::getDb());//注入db连接 $example->getList(); class Factory { public static function getExample(){ $example = new example(); $example->setDb(Factory::getDb());//注入db连接 $example->setFile(Factory::getFile());//注入文件处理类 $example->setImage(Factory::getImage());//注入Image处理类 return $expample; } } 实例化example时变为 $example=Factory::getExample(); $example->getList(); */ header("Content-Type:text/html;charset=utf-8"); class Di{ private $_factory; public function set($id,$value){ $this->_factory[$id] = $value; } public function get($id){ $value = $this->_factory[$id]; return $value(); } } class User{ private $_username; function __construct($username="") { $this->_username = $username; } function getUserName(){ return $this->_username;//$this->_username = $username; } } $di = new Di(); $di->set("zhangsan",function(){ return new User(‘张三‘); }); //$this->_factory[‘zhangsan‘] = new User(‘张三‘); $di->set("lisi",function(){ return new User("李四"); }); //$this->_factory[‘lisi‘] = new User(‘李四‘); echo $di->get("zhangsan")->getUserName();// $value = $this->_factory[‘zhangsan‘] = new User(‘张三‘)->getUserName(); echo $di->get("lisi")->getUserName();// $value = $this->_factory[‘lisi‘] = new User(‘李四‘)->getUserName(); /* $data = new User(‘张三‘); echo $data->getUserName(); */
时间: 2024-10-23 14:27:53