What are the New Features in PHP 8.1

Category
Website
Reading
3 mins
Views
1.2K
Posting
03 Aug 2022

On the official website, PHP finally released a new update with version 8.1 on November 25, which previously had the latest update with PHP 8. In this latest update, PHP added several additional new features, minor bug fixes and performance improvements.

Some of the lists of these features are Enumerations, Readonly Properties, Fibers, Pure Intersection Types, First Class Callable, Final Class Constants, Never Return Type, the addition of new functions array_is_list, fsync and fdatasync. In this article, we will discuss one by one what are these features? let's see:

 

 

What are the New Features in PHP 8.1

 

1. Enumerations

Enumerations allow developers to define their own data types or values. This is especially helpful when the developer is going to define a model and validate the process against those values in a shorter way, example syntax:

enum UserStatus: string
{
    case pending = "P";
    case active = "A";
    case cancel = "C";

    public function label(): string
    {
        return match ($this) {
            static::suspended => "Pending",
            static::active => "Active",
            static::cancel => "Cancel"
        };
    }
}

 

2. Readonly Properties

This new feature allows developers to mark processes as readonly on class properties, where the property can only be written once and cannot make further changes.

Readonly properties allow developers to directly expose public readonly properties without fear of breaking other class variants and avoiding writing the same code over and over (boilerplate). Example syntax:

class Try {
   public readonly string $property;

   public function __construct(string $property) {
     $this->property = $property;
   }
}

$test = new Try('test');
var_dump($test->property);

 

3. Fibers

Fibers is a mechanism to facilitate simultaneous commands, can pause, start, stop and resume multiple commands/executions without affecting other functions. Example syntax:

$fiber = new Fiber(function() : void {
   Fiber::suspend();
   echo "Fiber is running!";
});
$fiber->start();
$fiber->resume();

 

4. Pure Intersection Types

The PHP system now understands intersection. Pure Intersection Types are useful when calling code with instance methods defined by two interfaces. Where previously, developers needed to create new interfaces to extend both the desired interfaces and this was not practical. This feature is also used to declare multiple constraints at the same time. Example syntax:

# PHP 8.0
interface CountableString extends Countable, Stringable { }

public function countNumber(CountableString $value) : void {
  echo "$value: " . count($value);
}

#PHP 8.1
public function countNumber(Countable&Stringable $value) : void {
  echo "$value: " . count($value);
}

 

5. First Class Callable

Callable is now the main class in the PHP language. This means that developers can directly assign functions to variables instead of using Closure::fromCallable. First Class Callable is used to overwrite a value into a function by making the function callable. Example syntax:

# PHP 8.0
$built = Closure::fromCallable("array_map");
$method = [$this, "fetchData"];

# PHP 8.1
$built = array_map(...);
$method = $this->fetchData(...);

 

6. Final Class Constants

The value marker (Final) in constant is now supported in PHP 8.1. This allows developers to mark constants to avoid unwanted values in class instances. In previous versions, child classes were free to override constant values inherited by the parent class. Example syntax:

# PHP 8.0
class MainClass {
  public const NUMBERCONSTANT = 1;
}
class ChildClass extends MainClass {
  public const NUMBERCONSTANT = 2;
}

# PHP 8.1
class MainClass {
  final public const NUMBERCONSTANT = 1;
}
class ChildClass extends MainClass{
  public const NUMBERCONSTANT = 2;
}

 

7. Never Return Type

This new feature aims to stop program execution by using triggers such as exit() or die() functions to display error messages. The never function can protect a function from ever returning and can stop an endless loop. Example syntax:

function redirectURL(string $uri): never {
   header('Location: ' . $uri);
   exit();
}

 

8. New function array_is_list

Arrays in PHP can hold multiple keys in integers or strings. Developers will be efficient at checking if a particular entry is an array. But it's not easy to check if the entry has an array that doesn't have an offset, an unordered key and so on. In other words, the developer cannot determine if the array is a list.

The new function array_is_list can check the keys in an array that are in order and sequentially starting from 0. This function will return true, if all are met and detect an empty array. Example syntax:

// example returns true in array_is_list
array_is_list([]); // true
array_is_list([1, 2, 3]); // true

// example returns false in array_is_list
array_is_list([1 => 'cat', 'dog']); // false (first key offset is not 0)
array_is_list([1 => 'cat', 0 => 'dog']); // false (keys are not sequential)

This function strictly determines the order of the keys before continuing the code execution process.

 

9. New functions fsync and fdatasync

Finally in the update of PHP 8.1, PHP has implemented this function into their language, because PHP is one of the other languages that have not implemented this function.

The fsync() function is actually almost the same as the fflush() function, but there are significant differences. The fflush() function dumps the app's internal buffers to the OS and the fsync() function ensures that the internal buffers are dumped into physical storage. Example syntax:

$docs = 'document.txt';

$doc = fopen($docs, 'rb');
fwrite($doc, 'Document info');
fwrite($doc, "\r\n");
fwrite($doc, 'More info');

fsync($doc);
fclose($doc);

Meanwhile, the fdatasync() function is used to synchronize data in a fast way, without having to make sure with meta data that is not considered important enough.

 

Conclusion

Some of the new features that are present in PHP 8.1 are quite interesting for us to learn and apply to our applications. Of course, to make it easier for developers to make websites stable and fast. Do you want to directly migrate to this 8.1 version?

Share