Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

 PHP 8.1 new features

The technology world is moving forward, and the same holds for PHP too. PHP 8.0 brought many new features, performance improvements, and changes such as the new JIT compiler.  Now, PHP 8.1 will be released on November 25, 2021, with some exciting features. Let’s see the amazing new features of PHP 8.1.

New Features in PHP 8.1-

  1. Enums-

PHP 8.1 is adding support for enums. They’re user-defined data types consisting of a set of possible values. One of the most common examples in a programming language is the boolean type with true and false as possible values. According to the RFC, enums in PHP will be restricted to “unit enumerations”. According to the PHP team’s survey, it has been found that you can categorize enumerations into three categories- Fancy Constants, fancy Objects, and full Algebraic Data Types (ADTs).

PHP implements “Fancy Objects” enums so as to extend it to full ADTs in the future. Conceptually and semantically, it is modeled after enumerated types in Swift, Rust, and Kotlin, though it’s not modeled on any of them. RFC makes use of the famous analogy of suits to explain how it’ll work:

enum Suit {

  case Hearts;

  case Diamonds;

  case Clubs;

  case Spades;

}

Here, enum defines four possible values: Hearts, Diamonds, Clubs, and Spades. One can access those values using syntax: Suit::Hearts, Suit::Diamonds, Suit::Clubs, and Suit::Spades.

As enums are built atop classes and objects, this usage may seem familiar. They have almost the same requirements and behave similarly. Enums share the same namespaces as interfaces, traits and classes. Also, you can define Backed Enums if you want to give a scalar equivalent value to any cases. But, backed enums can only have only one type, either int or string (never both)

enum Suit: string {

  case Hearts = ‘H’;

  case Diamonds = ‘D’;

  case Clubs = ‘C’;

  case Spades = ‘S’;

}

Besides, all different cases of backend enum must have a unique value. You can never mix pure and backed enums.

2. Fibres-

Fibres are PHP’s way of handling parallelism through virtual threads (or green threads). It tries to eliminate the difference between synchronous and asynchronous code by allowing PHP functions to hinder without influencing the entire call stack. You can use Fibres to develop full-stack, interruptible PHP functions that you can use to implement cooperative multitasking in PHP. As Fibres pause the execution stack, you can rest assured knowing that it won’t impact rest of the code.

To illustrate the Fibres use, its RFC uses the simple example-

$fiber = new Fiber(function (): void {

    $value = Fiber::suspend(‘fiber’);

    echo “Value used to resume fiber: “, $value, “\n”;

});

$value = $fiber->start();

echo “Value from fiber suspending: “, $value, “\n”;

$fiber->resume(‘test’);

In the above code, you’re creating “fibre” and immediately suspending it with string fibre. The echo statement serves as a visual cue for fibre’s resumption. Retrieve this string value from the call to $fiber->start(). Resume the fibre with string “test”, that is returned from call to Fiber::suspend(). The complete code execution results in an output that reads –

Value from fiber suspending: fiber

Value used to resume fiber: test

Most of the PHP programmers will never deal with Fibres directly. Considering the performance benefits, you can expect PHP libraries and frameworks to leverage this new feature. 

3. New fsync() and fdatasync() Functions-

PHP 8.1 adds new file system functions named as- fsync() and fdatasync(). It’ll seem familiar for those used to Linux functions of the same name because they’re related as implemented for PHP. fsync function is just like PHP’s existing fflush() function, however it differs in one way. fflush flushes the app’s internal buffers to the OS, fsync() goes one step further and also ensures that internal buffers are flushed to physical storage. This ensures a complete and persistent write so that one can retrieve data even after an app or system crash.

How to use it?-

$doc = ‘kinsta.txt’;

$kin = fopen($doc, ‘ki’);

fwrite($kin, ‘doc info’);

fwrite($kin, “\r\n”);

fwrite($kin, ‘more info’);

fsync($kin);

fclose($kin);

Including the fsync() call at the end ensures that any data held in PHP’s or OS’s internal buffer gets written to storage. Other code execution are blocked until then. fdatasync()is used to sync data but not necessarily metadata. For data whose metadata is not important, this function call makes the writing process very rapid. 

4. New array_is_list() Function-

PHP arrays can hold both integer and string keys meaning that you can use it for lists, hash tables, dictionaries, collections, stacks, queues and so on. One can have arrays within arrays, creating multidimensional arrays. You can check whether a specific entry is an array. It is not that much simple to check any missing array offsets, out-of-order keys and so on. Simply, you can’t verify immediately whether an array is a list.

array_is_list() function checks whether an array’s keys are in sequential order without any gaps. If all the conditions are satisfied, it’ll return true. Have a look at some of the examples of using it with true and false conditions met:

// true array_is_list() examples

array_is_list([]); // true

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

array_is_list([‘cats’, 2, 3]); // true

array_is_list([‘cats’, ‘dogs’]); // true

array_is_list([0 => ‘cats’, ‘dogs’]); // true

array_is_list([0 => ‘cats’, 1 => ‘dogs’]); // true 

// false array_is_list() examples 

array_is_list([1 => ‘cats’, ‘dogs’]); // as first key isn’t 0

array_is_list([1 => ‘cats’, 0 => ‘dogs’]); // keys are out of order

array_is_list([0 => ‘cats’, ‘bark’ => ‘dogs’]); // non-integer keys

array_is_list([0 => ‘cats’, 2 => ‘dogs’]); // gap in between keys

PHP array list with out-of-order keys are a source of bugs. Using this function to enforce adherence to list necessities prior to moving ahead with code execution is a great addition to PHP.

5. New $_FILES: full_path Key for Directory Uploads-

PHP maintains a large number of predefined variables to track lots of things. One of them is $_FILES variable that holds an associative array of items uploaded through the HTTP POST method. PHP

Those changes in PHP 8.1 including new key named full_path to the $_FILES array. With the use of this new data, you can store relative paths or duplicate the exact directory structure on the server.

Test this data by outputting the $FILES array using the var_dump($_FILES);  command.

6. The never Return Type-

PHP 8.1 inlcudes new return type called never. It is helpful to use in functions that always exit or throw. According to the RFC, URL redirect functions that always exit are great example of its use:

function redirect(string $uri): never {

    header(‘Location: ‘ . $uri);

    exit();

}

function redirectToLoginPage(): never {

    redirect(‘/login’);

}

Never declared function should satisfy three conditions:

  • It shouldn’t have the return statement defined explicitly
  • It must end its execution with an exit statement (explicitly or implicitly).
  • It shouldn’t have the return statement defined implicitly (e.g. if-else statements).

never Return type shares lots of similarities with void return type. It ensures that the function or method doesn’t return a value. BUt it differs by stricter rules. For instance, void- declared function can still return without explicit value, but you can’t do the same with never-declared function. 

Also, never is defined as a “bottom” type. So any class method declared never can “never” change its return type to else. But you can extend void declared method with never declared method.

7. New MYSQLI_REFRESH_REPLICA Constant-

PHP 8.1 adds a new constant called MYSQLI_REFRESH_REPLICA.It is like existing MYSQLI_REFRESH_SLAVE constant. This change was introduced in MySQL 8.0.23 to address racial insensitivity in tech vocabulary. Apps and programmers can still use the older constant. 

8. First-Class Callable Syntax-

PHP 8.1 includes a first-class callable syntax to override existing encodings using strings and arrays. Apart from this, creating a clean Closure, this new syntax is also accessible by static analysis tools and respects the declared scope. For instance-

$fn = Closure::fromCallable(‘strlen’);

$fn = strlen();

$fn = Closure::fromCallable([$this, ‘method’]);

$fn = $this->method()

$fn = Closure::fromCallable([Foo::class, ‘method’]);

$fn = Foo::method();

Here all the expression pairs are equivalent. The (..) syntax is like to the argument unpacking syntax (…$args). Except here, the arguments are not yet filled in.

Final Words-

PHP 8.1 will release on november 2021 and you can experience these amazing features. These are just a few. If you’re thinking of building a web solution with PHP, knowing the above features will surely help you to build a web solution with the latest features. You can hire PHP developers from the Solace team for effective web development. Connect with Solace and get a free quote for web development with PHP. We will be happy to help you.

The post  PHP 8.1 new features first appeared on Blog.



This post first appeared on Confused About- Native VS Hybrid App Development: Which One To Choose?, please read the originial post: here

Share the post

 PHP 8.1 new features

×

Subscribe to Confused About- Native Vs Hybrid App Development: Which One To Choose?

Get updates delivered right to your inbox!

Thank you for your subscription

×