T
T
topuserman2020-09-02 16:10:03
PHP
topuserman, 2020-09-02 16:10:03

Interface when inheriting a method: how to do it right?

interface IUser {
    public static function getById(): IUser;
}
interface IAdmin extends IUser { ... }

class User implements IUser {
      public static function getById(): IUser {  ... }
}

class Admin extends User  implements IAdmin {
   // ...
}


There is a base class User , from which other classes, such as Admin , inherit .
The getById method is implemented only in the base class, and the ability is needed so that the heirs can also use this method, because heirs are the same users, with only some additions.

The get method must return its own object, and there is a problem with the implementation:
when the User class returns new self, then everything works fine, because the expected data type is IUser , and the User class implements just that.

But if the heirs will do return self , for example the Admin class, then the result will be of type IAdmin , and the get method expects type IUser .

The problem arises because of covariance and contravariance.
Can you please tell me how to solve my problem, and which one is preferable?

I am using php 7.3. I know that in php 7.4 the return type self is implemented.
those. you can do this: I want every child that uses the getById method to return self, but the expected type for the method is valid. UPD I also most likely have errors. should not be return self , but return static ? but that still doesn't solve the problem. public static function getById(): self;





Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Adamos, 2020-09-02
@Adamos

There is a base User class from which other classes are inherited, such as Admin.

In vain. Admin is not a type of user, it is a well-defined role on the site associated with a specific user. Inheritance does not make sense here, the site administration logic and the site user do not intersect.

D
Daria Motorina, 2020-09-02
@glaphire

There is a discussion
here https://stackoverflow.com/questions/39068983/php-7...
Maybe we should abandon statics and return IUser ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question