实现类:

复制代码代码如下所示:

< PHP



类容器

{

保护设置为数组(美元);



公共函数集(抽象,$ = NULL)

{

如果($ = NULL){

$具体=抽象;

}



美元->设置{ $摘要} = $混凝土;

}



公共函数获取(抽象$,参数=数组()))

{

如果(!isset(美元->设置{ $摘要})){

返回null;

}



返回这个->建立(美元->设置摘要} { $,$参数);

}



公共函数构建($,$,$)

{

如果($具体实例关闭){

返回$ $($,$);

}



反射器=新reflectionclass美元($混凝土);



如果(!$反射器-> isinstantiable()){

抛出异常(类不能实例化具体} { $ );

}



构造函数=美元美元-> getconstructor反射();



如果(is_null($构造函数)){

返回的反射-> newInstance();

}



构造函数参数=美元美元->得到相机的参数();

依赖=美元美元-> getdependencies($参数);



返回的反射-> newinstanceargs(美元的依赖);

}



公共功能getdependencies($参数)

{

$ =数组();

foreach($参数达参数){

依赖美元美元=参数-> getClass();

如果($ = NULL){

如果($参数-> isdefaultvalueavailable()){

{ } =美元美元依赖参数-> getdefaultvalue();

{人}

抛出新的异常(不能解析类依赖性参数$ });

}

{人}

$依赖项{;

}

}



返回$依赖项;

}

}



实例的实现:

复制代码代码如下所示:

< PHP



require'container PHP的;





接口myinterface { }

Foo类的实现myinterface { }

类杆实现myinterface { }

Baz类

{

公共功能__construct(myinterface $ Foo)

{

$;

}

}



$容器=新容器();

集装箱->设置('baz美元,'baz);

集装箱->设置('myinterface美元,'foo);

巴兹=美元美元集装箱->得到('baz);

print_r($ Baz);

集装箱->设置('myinterface美元,'bar);

巴兹=美元美元集装箱->得到('baz);

print_r($ Baz);