PHP 8.0 : `static` return type
12, July 2021

Recently, usage of named construct has increased within PHP ecosystem. Named Construct gives us a readable and flexible way to create object from different types of data. With static return type, we now can properly define return type of these named construct.


Lets see what are named constructs?

<?php

class User
{
  public function __construct(private string $name, private string $email, private int $age)
  {    
  }
 
  public static function fromJson(string $json)
  {
      $data = json_decode($json);
      
      return new static($data->name, $data->email, $data->age);
  }
}

in above snippet, we can create User object from a json string (maybe from API) by calling User::fromJson() named construct.

As these constructs can have meaningful name, its much more readable. Also, this way we can have multiple way to construct User object.


Before PHP 8.0, named construct couldn't have proper return type. We could define self return type but it wouldn't be proper if that class is being extended by a child class. Using class name as return type have same limitation.

To indicate that a method returns instance of same class, we can now use static return type:

  public static function fromJson(string $json): static // <-- static return type
  {
      $data = json_decode($json);
      
      return new static($data->name, $data->email, $data->age);
  }


RFC: https://wiki.php.net/rfc/static_return_type


Write comment about this article: