_instances[$name])){ // no \Closure
return $this->_instances[$name];
}
//
if(!isset($this->_bindings[$name])){
return null;
}
$concrete = $this->_bindings[$name]['class'];//
$obj = null;
//
if($concrete instanceof \Closure){
echo "---"; print_r($name); echo "---";
$obj = call_user_func_array($concrete,$params);
}
//
elseif(is_string($concrete)){
if(empty($params)){
$obj = new $concrete;
}else{
// ,
$class = new \ReflectionClass($concrete);
$obj = $class->newInstanceArgs($params);
}
}
// , _instances ,
if($this->_bindings[$name]['shared'] == true && $obj){
$this->_instances[$name] = $obj;
}
print_r($obj);
return $obj;
}
//
public function has($name){
return isset($this->_bindings[$name]) or isset($this->_instances[$name]);
}
//
public function remove($name){
unset($this->_bindings[$name],$this->_instances[$name]);
}
//
public function set($name,$class){
$this->_registerService($name, $class);
}
//
public function setShared($name,$class){
$this->_registerService($name, $class, true);
}
//
private function _registerService($name,$class,$shared=false){
$this->remove($name);
if(!($class instanceof \Closure) && is_object($class)){
$this->_instances[$name] = $class;
}else{
$this->_bindings[$name] = array("class"=>$class,"shared"=>$shared);
}
}
//ArrayAccess ,
public function offsetExists($offset) {
return $this->has($offset);
}
//ArrayAccess , $di[$name]
public function offsetGet($offset) {
return $this->get($offset);
}
//ArrayAccess , $di[$name]=$value ,
public function offsetSet($offset, $value) {
return $this->set($offset,$value);
}
//ArrayAccess , unset($di[$name])
public function offsetUnset($offset) {
return $this->remove($offset);
}
}
header("Content-Type:text/html;charset=utf8");
class A{
public $name;
public $age;
public function __construct($name=""){
$this->name = $name;
}
}
$di = new Di();
// a1
$di->set('a1',function($name=""){
echo "--1-"; print_r($name); echo "--1-";
return new A($name);
});
//
$di->set('a2','A');
//
$di->set('a3',new A(" "));
echo "
";
print_r($di);
$a1 = $di->get('a1',array(" "));
echo $a1->name."
";//
$a1_1 = $di->get('a1',array(" "));
echo $a1->name."w
";//
echo $a1_1->name."
";//
$a2 = $di->get('a2',array(" "));
echo $a2->name."
";//
$a2_1 = $di->get('a2',array(" "));
echo $a2->name."
";//
echo $a2_1->name."
";//
$a3 = $di['a3'];//
echo $a3->name."
";//
http://www.cjjjs.com/paper/gzsh/2017217135916798.aspx