-->

static return type in PHP 7 interfaces

2020-05-31 07:01发布

问题:

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?

回答1:

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.



回答2:

2020 update

Static return types will be introduced in PHP 8.