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 aBigInteger
BigDecimal::plus()
must return aBigDecimal
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?
2020 update
Static return types have been introduced in PHP 8.