<?php
/*依賴注入約束注入的類必需是實現visit接口的類*/
interface visit{
public function go();
}
class car implements visit{
public function go(){
echo '輪子跑';
}
}
class train{
public function go(){
echo '動車組';
}
}
class trive{
public $visit;
function __construct(visit $visit){//visit 接口的實現類
$this->visit = $visit;
}
public function triveType(){
$this->visit->go();
}
}
$car = new car();
/*$trive = new trive($car); //旅行類注入轎車實例
$trive->triveType(); //輸出旅行方式
*/
$train = new train();
$trive = new trive($train); //旅行類注入火車實例
$trive->triveType();//報錯 因為注入的train實例沒有實現visit接口