duancuo1234 2014-11-20 10:54
浏览 62
已采纳

将接口注入php类

So I have the following interface defined for a car:

interface FuelTank
{
    public function useFuel();
}

interface WaterTank
{
    public function useWater();
}

interface CarInterface extends FuelTank, WaterTank
{
    public function drive($miles);

    public function setFuelTank(FuelTank $tank);

    public function setWaterTank(WaterTank $tank);
}

I have tried to build a class that implements and complies to the CarInterface but I'm having trouble with the injection of the FuelTank and Watertank dependancies. This is the class I came up with:

class Car implements CarInterface
{
    protected $fuelTank;
    protected $waterTank;

    public function drive($miles)
    {
        return $miles;
    }

    public function useWater()
    {

    }

    public function useFuel()
    {

    }

    public function setFuelTank(FuelTank $tank)
    {
        $this->fuelTank = $tank;
    }

    public function setWaterTank(WaterTank $tank)
    {
        $this->waterTank = $tank;
    }
}

Now when I run the following:

$car = new Car;
$car->setFuelTank(new FuelTank);

I get this message:

Fatal error: Cannot instantiate interface FuelTank

I also can't declare the class FuelTank as I get this error instead:

Fatal error: Cannot redeclare class FuelTank

Can someone help me understand how to correctly implement the interface above and what's going on here?

  • 写回答

1条回答 默认 最新

  • dongtui9168 2014-11-20 10:58
    关注

    You should rename the interface FuelTank to FuelTankInterface and declare a class FuelTank which implements the FuelTankInterface. An interface cannot be instantiated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法