依赖注入

首先有个接口

  interface Visit {

    public function go ();

  }

然后有三个类Leg,Car,Train

  class Leg implements Visit {

    public function go (){

      echo "walt to 新疆";

    }

  }

  class Car implements Visit {

    public function go () {

      echo "drive car to 新疆";

    }

  }

  class Train implements Visit {

    public function go () {

      echo "go to 新疆 by train";

    }

  }

依赖注入:

  class Traveller {

    protected $trafficTool;

    public function  __construct(Visit $traffic){

      $this->trafficTool = $traffic;

    }

    public function visit() {

      $this->trafficTool->go();

    }

  }

  $traffic = new Leg();

  $visit = new Traveller($traffic);

  $visit->visit();

posted @ 2017-07-04 14:07  叨叨斋  阅读(128)  评论(0编辑  收藏  举报