New static Return Type in PHP 8.0

New static Return Type in PHP 8.0

PHP allows defining type declarations for parameters, return values, and properties. In PHP 7.0 and newer versions, we can use self and parent return types for class methods. Since PHP 8.0, we can also use static return type. The most common use cases are:

  • Named constructor idiom - static methods are used to create objects instead of constructor.

User.php

<?php

class Request
{
    private string $body;

    public static function fromArray(array $array): static
    {
        return new static($array['body']);
    }

    private function __construct(string $body)
    {
        $this->body = $body;
    }
}
  • Mutation of immutable objects - methods are used to return a modified instance by cloning the original instance.

MailSender.php

<?php

class MailSender
{
    private DateTimeZone $timeZone;

    public function withTimeZone(DateTimeZone $timeZone): static
    {
        $new = clone $this;
        $new->timeZone = $timeZone;

        return $new;
    }
}
  • Fluent methods - are methods that returns an instance of a class to allow method chaining.

Person.php

<?php

class Person
{
    private string $name;

    public function setName(string $name): static
    {
        $this->name = $name;
        
        return $this;
    }
}

There are some important notes:

  • The static type is only allowed to use as return type. It cannot be used to define type for parameters and properties.
  • The static return type is only allowed to use for class methods. It cannot be used for functions or closures to define return type.

Leave a Comment

Cancel reply

Your email address will not be published.