39

PHP: rfc:static_return_type

 4 years ago
source link: https://wiki.php.net/rfc/static_return_type
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

The static special class name in PHP refers to the class a method was actually called on, even if the method is inherited. This is known as “late static binding” (LSB). This RFC proposes to make static also usable as a return type (next to the already usable self and parent types).

There are a number of typical use-cases where static return types appear (currently in the form of @return static).

One are named constructors:

class Test {
    public function createFromWhatever($whatever): static {
        return new static($whatever);
    }
}

Here we want to specify that XXX::createFromWhatever() will always create an instance of XXX, not of some parent class.

Another are withXXX() style interfaces for mutating immutable objects:

class Test {
    public function withWhatever($whatever): static {
        $clone = clone $this;
        $clone->whatever = $whatever;
        return $clone;
    }
}

Here we want to specify that $foobar->withWhatever() will return a new object of class get_class($foobar), not of some parent class.

Finally, the likely most common use case are fluent methods:

class Test {
    public function doWhatever(): static {
        // Do whatever.
        return $this;
    }
}

Here we actually have a stronger contract than in the previous two cases, in that we require not just an object of the same class to be returned, but exactly the same object. However, from the type system perspective, the important property we need is that the return value is an instance of the same class, not a parent class.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK