I\'m trying to specify two interfaces for class A that returns instances of class B, and for class B itself.
I\'m declaring return types on the interface.
Sa
This is not possible with any version of PHP lower than 7.4.
If your interface contains:
public function get( $key ) : ElementInterface;
Then your class needs to be:
class MyRepository implements RepositoryInterface {
public function get( $key ) : ElementInterface {
returns new MyElement();
// which in turn implements ElementInterface
}
}
The declaration of a class implementing an interface has to match exactly the contract laid out by the interface.
By declaring that it has to return a particular interface instead of an specific implementation, you are giving you leeway on how to implement it (now you could return MyElement
or AnotherElement
as long as both implemented ElementInterface
); but the method declaration has to be the same anyway.
See it working here.
Starting with PHP 7.4, due to be released in November 2019, covariance will be supported for return types. By then, this would work.