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