10分钟快速理解依赖注入

本文通过具体示例展示了PHP中抽象类与接口的应用。利用这些特性实现了自驾游与徒步旅行的不同行为,并通过依赖注入的方式选择不同的旅行方式。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值