PHP覆盖子类中的接口签名

时间:2016-08-03 16:46:05

标签: php oop inheritance abstract-class signature

我有以下接口/类:

class Part {}
class Engine extends Part{}

interface CarsInterface {
    public function selectTimeLine(Part $object);
}

abstract class Car implements CarsInterface {}

class Hybrid extends Car {
    public function selectTimeLine(Engine $object) {}
}

如果Engine是" Part"的子类,为什么我不能在子签名(Hybrid Class)中使用Engine对象? (我知道它可能在Java中...)

在PHP中实现此功能的正确方法是什么? THX

2 个答案:

答案 0 :(得分:3)

是的,PHP很糟糕。 =)

如果我没弄错的话,你需要这样的东西:

interface SomeInterface {
}

class Part implements SomeInterface  {}
class Engine extends Part implements SomeInterface{}

interface CarsInterface {
    public function selectTimeLine(SomeInterface $object);
}

abstract class Car implements CarsInterface {}

class Hybrid extends Car {
    public function selectTimeLine(SomeInterface $object) {}
}

答案 1 :(得分:1)

简而言之,界面旨在通过为对象设置特定指令来为您提供这些限制。这种方式在检查对象的功能时或使用instanceof时,您始终可以接收指定的内容。

没有"正确"实现你想要做的事情的方法,但建议的方法是使用接口键入提示而不是特定的类定义。

这样,您始终可以保证提供的对象的可用方法。

interface TimeLineInterface { }

class Part implements TimeLineInterface { }

class Engine extends Part { }

interface CarInterface
{
    public function selectTimeLine(TimeLineInterface $object);
}

abstract class Car implements CarInterface { }

class Hybrid extends Car
{
   public function selectTimeLine(TimeLineInterface $object) { }
}

如果你想强制接受对象方法的特定类型的对象,你需要像这样检查对象实例。

class Hybrid extends Car
{
   public function selectTimeLine(TimeLineInterface $object) 
   {
       if (!$object instanceof Engine) {
            throw new \InvalidArgumentException(__CLASS__ . '::' . __FUNCTION__ . ' expects an instance of Engine. Received ' . get_class($object));
       }
   }
}