samedi 3 août 2019

Abstract class or interface where declaration method signature allows type hinting of child classes

TLDR: The add method with a child object argument doesn't match the implementation which calls the parent class. Is there a way around this?

My original thinking was to create an interface for Collection.

interface Collection {
   public function add( ValueObjects $obj ) : bool;
}

abstract class ValueObjects {}

class User extends ValueObjects {
}

And the implement it on a specific implementation of ValueObjects.

class UserCollection implements Collection {
  public function add( User $user ) : bool 
  {
     return true;
  }
}

This obviously throws an error that Declaration should be compatible with Collection. Is there a way to achieve the same result to allow children objects in the signature? I tried with abstract classes and no result.

It would be even better if I didn't have to extend the abstract ValueObjects class.

Thanks for sharing your knowledge SO community.

PS... reviewed this question , decorator and composition patterns. I either missed it or my question is a little different.

Aucun commentaire:

Enregistrer un commentaire