<?php
class DI
{
private $container; public function set($key, $obj, ...$args)
{
$this->container[$key] = [
'obj' => $obj,
'params' => $args
];
} public function delete($key)
{
unset($this->container[$key]);
} public function clear()
{
$this->container = [];
} public function get($key)
{
if (isset($this->container[$key])) {
$res = $this->container[$key];
if (is_object($res['obj']) && !is_callable($res['obj'])) {
return $res['obj'];
} elseif (is_callable($res['obj'])) {
$this->container[$key]['obj'] = call_user_func($res['obj']);
return $this->container[$key]['obj'];
} elseif (is_string($res['obj']) && class_exists($res['obj'])) {
$reflection = new \ReflectionClass ($res['obj']);
$ins = $reflection->newInstanceArgs($res['params']);
$this->container[$key]['obj'] = $ins;
return $this->container[$key]['obj'];
} else {
return $res['obj'];
}
} else {
return null;
}
}
} class Test1
{
public function show()
{
echo "hello World \n";
}
} class Test2
{
public function __construct($name)
{
echo '我是参数' . $name . PHP_EOL;
} function show()
{
echo "我是test2";
}
} class Test4
{
public function show()
{
echo "test4";
}
} $DI = new DI(); $DI->set('name', 'zhangsan'); echo "注入字符串" . $DI->get('name') . PHP_EOL; $test1 = new Test1(); $DI->set('test1', $test1); echo "获取对象" . $DI->get('test1')->show() . PHP_EOL; $DI->set('test2', Test2::class, 'zhangsa'); $DI->get('test2')->show(); $DI->set('test3', function () {
return new Test4();
}); $DI->get('test3')->show();

最新文章

  1. 前端组件化Polymer入门教程(8)——事件
  2. fc23升级fc24及字体问题解决
  3. springrain 1.1 发布,spring 的极简封装
  4. [转载]Web 研发模式演变
  5. MFC学习 画图设置字体按钮风格
  6. 【BZOJ】【1021】【SHOI2008】Dept循环的债务
  7. bzoj2801
  8. springMVC数据封装成POJO
  9. CSS随记
  10. Android从raw、assets、SD卡中获取资源文件内容
  11. android学习一些帖子
  12. UVA 11769 All Souls Night 的三维凸包要求的表面面积
  13. 【IE6的疯狂之四】IE6文字溢出BUG
  14. 使用Dockerfile构建镜像-Docker for Web Developers(5)
  15. Sublime text 3搭建Python开发环境
  16. 第2阶段——编写uboot之启动内核和制作Makefile(2)
  17. tcp 网络编程
  18. Python学习笔记七
  19. tensorflow会话控制-【老鱼学tensorflow】
  20. python 报错 TabError: inconsistent use of tabs and spaces in indentation

热门文章

  1. echarts学习(上)
  2. golang中jwt使用
  3. 好玩的WPF第三弹:颤抖吧,地球!消失吧,地球!
  4. WPF中StringFormat的用法
  5. Vertica变化Local时间到GMT时间
  6. 多线程——继承Thread类别
  7. 网络库Asio交叉编译(Linux生成ARM)
  8. SGI STL中内存池的实现
  9. 深入解析Android关机
  10. 快速写入Xml文件