php模拟实现依赖注入,为什么注释的代码会报错,想了很久加百度过还是不懂
月影流觞 2016-05-03 07:59:50 详细代码如下:
<?php
//模拟实现依赖注入
header("content-type:text/html;charset=utf-8");
interface Car{
public function getBrand();
public function run();
}
class BMWCar implements Car{
private $myBrand="宝马";
public function getBrand(){
return $this->myBrand;
}
public function run(){
echo "<BR>".$this->myBrand." is running"."<BR>";
}
}
class Human{
private $car;
public function getCar(){
return $this->car;
}
public function setCar(Car $car){
$this->car=$car;
}
public function myCarRun(){
$this->car->run();
}
}
interface BeanFactory{
public function getBean($id);
}
class ApplicationContext implements BeanFactory{
private $beans=array();
public function __construct(){
$xmlstr=simplexml_load_file('beans.xml');
print_r($xmlstr);
echo "<BR>";
//$xml=new SimpleXMlElement('beans.xml',0,true);
foreach ($xmlstr->bean as $key => $value) {
$id=$value['id'];
$class=$value['class'];
$reflect=new ReflectionClass("$class");
$instance=$reflect->newInstanceArgs();
foreach ($value as $key1 => $value1) {
if($key1=='property'){
$propertyName=$value1['name'];
$bean=$value1['bean'];
if(!isset($value1['bean'])){
$methodName='set'.ucfirst($propertyName);
$method=$reflect->getMethod($methodName);
$method->invoke($instance);
}
else{
var_dump($this->beans);
$propertyBean=$this->beans["$bean"];
//$propertyBean=$this->beans[$bean]; //这两种写法结果居然不同,注释里面的会报错,为什么
$methodName='set'.ucfirst($propertyName);
echo $methodName;
$instance->$methodName($propertyBean);
}
}
}
$this->beans["$id"]=$instance;
}
}
public function getBean($id){
return $this->beans[$id];
}
}
$context=new ApplicationContext();
$car=$context->getBean('c');
$car->run();
$human=$context->getBean('human');
$human->myCarRun();
?>
对应xml文件里的内容
<beans>
<bean id="c" class="BMWCar">
</bean>
<bean id="human" class="Human">
<property name="car" bean="c"></property>
<x name="bus"></x>
</bean>
</beans>
总觉得很费解,希望有心人可以帮忙,而且我也觉得这个问题很值得深入