<?php
class Container {
private $s=array();
function __set($k, $c) { $this->s[$k]=$c; }
function __get($k) { return $this->s[$k]($this); }
}
有了container类之后我们可以怎样管理A与B之间的依赖关系呢,用代码说话吧:
<?php
class A
{
private $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function doSomeThing()
{
//do something which needs class B
$b = $this->container->getB();
//to do
}
}
再将B类注入到容器类中:
$c = new Container();
$c->setB(new B());
还可以传入一个匿名函数,这样B类就不会在传入时就立即实例化,而是在真正调用时才完成实例化的工作
$c = new Container();
$c->setB(function (){
return new B();
});