PHP Class Method Inheritance

I'm trying to override a class' parent function with some changes. I have one argument that needs to be type-hinted on the parent and on the child it's a class that extends that type-hint:

class BaseObject { 
  //...
}

class NewObject extends BaseObject {
  //...
}

// -----------------------------------

class ParentClass {
  function method(BaseObject $obj) {
     //...
  }
}

class ChildClass extends ParentClass {
  function method(NewObject $obj) {
     //...
  }
}

PHP is returning:

Declaration of ChildClass::method(NewObject $obj) should be compatible with ParentClass::method(BaseObject $obj)

I find this kind of odd, since NewObject is an instance of the BaseObject.

Upvotes: 1

Views: 55

Answers (1)

Ary Wibowo
Ary Wibowo

Reputation: 539

I think that you need is an interface. If both class implement same interface, you can do Dependency Injection on the method that you want.

interface InterfaceName {
  //...
}

class BaseObject implements InterfaceName { 
  //...
}

class NewObject extends BaseObject implements InterfaceName {
  //...
}

class ParentClass {
  function method(InterfaceName $obj) {
     //...
  }
}

class ChildClass extends ParentClass {
  function method(InterfaceName $obj) {
     //...
  }
}

Reference : https://www.php.net/manual/en/language.oop5.interfaces.php

Upvotes: 1

Related Questions