您的位置:首页 > 其它

10分钟快速理解依赖注入

2016-12-13 16:39 477 查看
https://www.phpxy.com/article/200.html

<?php

interface travelinterface
{
public function __construct($speed, $distance);
public function run();
}

abstarct class travel implements travelinterface
{
protect $speed; 	//最高时速
protect $distance; 	//最远路程

public function __construct($speed, $distance)
{
$this->speed = $speed;
$this->distance = $distance;
}
}

class drive extends travel
{
public function run()
{
echo '自驾游';
}
}

class walk extends travel
{
public function run()
{
echo '徒步旅行';
}
}

class human
{
protect $travel;

public function __construct(travel $travel)
{
$this->travel = $travel;
}

// public function __construct()
// {
//        $this->travel = new drive(60,1000);
// }

public function traveling()
{
$this->traveling->run();
}
}

$travel = new drive(60, 1000);
$xiaoming = new human();
$xiaoming->traveling();

//配置
$config = [
"travel" => drive::class,
];
$travel = new $config["travel"](60,1000);
$xiaoming = new human($travel);
$xiaoming->traveling();


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: