PHP - Interface inheritance - declaration must be compatible

后端 未结 2 1067
小蘑菇
小蘑菇 2020-12-10 06:08

I have the interface:

interface AbstractMapper
{
    public function objectToArray(ActiveRecordBase $object);
}

And classes:



        
相关标签:
2条回答
  • 2020-12-10 06:21

    No, an interface must be implemented exactly. If you restrict the implementation to a more specific subclass, it's not the same interface/signature. PHP doesn't have generics or similar mechanisms.

    You can always manually check in code, of course:

    if (!($object instanceof Product)) {
        throw new InvalidArgumentException;
    }
    
    0 讨论(0)
  • 2020-12-10 06:38

    Another way of implementing this would be:

    class Executor
    {
        public function objectToArray(AbstractMapper $var)
        {
            $this->convert($var);
        }
    
        private function convert(Product $var)
        {
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题