Is there a way to redefine a type hint to a descendant class when extending an abstract class?

前端 未结 3 1709
名媛妹妹
名媛妹妹 2020-12-03 06:45

I will be using the following example to illustrate my question:

class Attribute {}

class SimpleAttribute extends Attribute {}



abstract class AbstractFac         


        
3条回答
  •  醉话见心
    2020-12-03 07:16

    Since PHP 7.4 it is allowed to use more specific type-hint in children classes by using interfaces

    interface OtherAttributeCompatibleInterface{};
    interface SimpleAttributeCompatibleInterface{};
    
    interface AllAttributesInterface extends OtherAttributeCompatibleInterface, SimpleAttributeCompatibleInterface{};
    
    
    class Attribute implements AllAttributesInterface{};
    
    class SimpleAttribute extends Attribute  implements SimpleAttributeCompatibleInterface{};
    
    
    abstract class AbstractFactory  {
        abstract public function update(AllAttributesInterface $n);
    }
    
    class SimpleFactory  extends AbstractFactory  {
      public function update (SimpleAttributeCompatibleInterface $n){
      }
    }
    

    Cause AllAttributesInterface inherits SimpleAttributeCompatibleInterface it is allowed to overwrite the update method from AbstractFactory by SimpleFactory.

提交回复
热议问题