1

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.

1
  • Do you have a question? Commented Jul 3, 2020 at 15:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is what I was looking for. I use interfaces a lot, but forgot to pass it as an argument type, somehow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.