10分钟快速理解依赖注入

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();

  

原文地址:https://www.cnblogs.com/lixiuran/p/6170530.html