<?php
class Db
{
public function __construct()
{
}
public function connect()
{
return "連線DB";
}
}
class Ioc
{
public static $reg = [];
/**
* @func 新增一個反轉的物件到容器中
* @param $name
* @param Closure $resolved
*/
public static function register($name, Closure $resolved)
{
static::$reg[$name] = $resolved;
}
/**
* @func 根據name返回實類
* @param $name
* @return mixed
*/ public static function resolve($name)
{
if (static::register($name)) {
$obj = static::$reg[$name];
return $obj();
}
}
}
//注入
//第二個引數是閉包
Ioc::register('db', function () {
new Db();
});
//反轉
$db = Ioc::resolve('db');
$db->connect();
本作品採用《CC 協議》,轉載必須註明作者和本文連結