Why is it not possible in PHP 7, to declare an interface with a static
return type?
Let's say I have the following classes:
interface BigNumber {
/**
* @param BigNumber $that
*
* @return static
*/
public function plus(BigNumber $that);
}
class BigInteger implements BigNumber { ... }
class BigDecimal implements BigNumber { ... }
I want to enforce the return type of the plus()
method to static
, that is:
BigInteger::plus()
must return a BigInteger
BigDecimal::plus()
must return a BigDecimal
I can declare the interface in the following way:
public function plus(BigNumber $that) : BigNumber;
But that doesn't enforce the above. What I would like to do is:
public function plus(BigNumber $that) : static;
But PHP 7, to date, is not happy with it:
PHP Parse error: syntax error, unexpected 'static' (T_STATIC)
Is there a specific reason for this, or is this a bug that should be reported?
PHP 8.0 allows static as a return type for class methods. PHP class methods can return self and parent in previous versions, but static was not allowed in PHP versions prior to 8.0. The newly allowed static return type allows to narrow down the return type to the called class.
In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared. int. float. bool. string. interfaces.
PHP 8.0 allows static as a return type for class methods. class Foo { public static function getInstance(): static { return new static(); } } PHP class methods can return self and parent in previous versions, but static was not allowed in PHP versions prior to 8.0.
The newly allowed static return type allows to narrow down the return type to the called class. The static return type helps classes with fluent methods (i.e the ones with return $this ), immutable classes (i.e return clone $this) or static methods that return an instance of the class itself.
Static return types have been introduced in PHP 8.
It's not a bug, it just doesn't make sense design-wise from an object-oriented programming perspective.
If your BigInteger
and BigDecimal
implement both BigNumber
, you care about the contract they fulfil. I this case, it's BigNumber
's interface.
So the return type you should be using in your interface is BigNumber
since anybody coding against that interface does not know anything else than members of that interface. If you need to know about which one is returned, the interface is perhaps too wide in the first place.
Note: programming languages with generics can achieve this effect by specifying the return type as the generic type, but PHP does not have generics and probably will not have in the near future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With