The State of Php 8: New Features and Changes

by Janeth Kent Date: 29-12-2020 php php8


PHP 8.0 has been released last November 26: let's discover together the main innovations that the new version introduces in this language.

PHP is one of the most popular programming languages in the world. Precisely its wide diffusion, has led many programmers to use it, especially for the development of server-side business logic of web applications.

Beyond the many criticisms that continues to receive, PHP is still among the top 10 most used languages in the world. And it is also for this reason that the innovations introduced in PHP 8.0 (released on November 26) have a significant importance in all communities of web developers.

Therefore, in this article we will try to summarize the main news of this recent version of PHP.

PHP JIT (Just in Time Compiler)

The most acclaimed feature is definitely the Just-in-time (JIT) Compiler which aims to improve performance and memory usage by compiling parts of the code directly at runtime. By doing so, the JIT compiler will be able to cache the version of code already interpreted, generating a machine language as output.

Performance improvements in PHP 8 thanks to JIT

Passing Arguments by Name

A new feature introduced in PHP 8 is that of named arguments, which will allow you to execute a function by passing an argument by name, and not simply by position. For example, let's imagine defining the following function:

 
function test(string $a, string $b, ?string $c = null, ?string $d = null)  
{      
/* … */  
}


We can now run the function like this:

 
test(b: 'arg1', a: 'arg2', d: 'arg3',

);


This makes the code more readable, without removing or limiting the possibilities provided by previous versions of the language. Already other programming languages allow passing arguments by name as well as by position (e.g. Python), and certainly this feature will please many developers.

Attributes


PHP 8 introduces attributes, often known in other languages as 'annotations'. It is basically a mechanism to add metadata to classes, which until now was only possible by inserting them inside multi-line comment blocks. In other words, in PHP 7 and earlier versions, we were forced to proceed in this way:

 
class PostsController
  {
/**
* @Route("/api/posts/{id}", methods={"GET"})
*/
public function get($id) { /* ... */ }
}
 

With the new version of PHP, the above code becomes similar to the following:

 
class PostsController
  {
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }
}
 

Constructor property promotion

Another simplification of the code regards the definition and promotion of the properties of a class directly inside the constructor. This modification (which also takes the syntax of Python and other languages) allows to significantly reduce the lines of code required for the definition of the structure of a class, as shown in the following code:

 
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
 

Union types

Union types are perhaps one of the most innovative new features of the new version of PHP. Because of PHP's dynamic typing, there are many cases where it may be useful to specify as many data types as possible for a parameter, rather than only being able to do so in annotations. The newly introduced syntax allows you to do exactly that, as shown in the code below:

 
public function foo(Classe1|Classe2 $input): int|float;


Note that the void type can never be part of a union type. Also, it is possible to specify unions of types that are nullable, either by using the |null syntax, or by question mark notation (?):

 
public function foo(ClasseX|null $foo): void;
public function bar(?ClasseY $bar): void;

php union types

Matching expression: Match

PHP 8 also introduces a new construct, very similar to the switch, identified by the match keyword. In some ways, you can consider it a sort of "big brother" of the switch, and the similarities should be quite intuitable from the following snippet:

 
$result = match($input) {
0 => "hello",
'1', '2', '3' => "world",
};


Among the features implemented by match, we mention the ability to return values, the fact that it does not require the presence of break statements, and the ability to combine multiple conditions.

php8 Match

Nullsafe operator

A new syntax has been introduced that avoids the verification that a variable or the return value of a method is null. The nullsafe operator allows you to implement this in a single line: every time the evaluation of an element fails, the execution of the whole chain of calls is interrupted, and the return value is null.

Here is an example:

 
$country = $session?->user?->getAddress()?->country;

php8 nullsafe

More consistent string and number comparisons

When comparing a numeric string, PHP 8 uses a number comparison. Conversely, when comparing a string that does not contain only numbers, string comparison is used, thus turning the numbers in the expression into strings.

php8 comparing string

Consistent error types for native functions

With the upgrade to PHP 8, many of the native PHP functions throw an error exception if parameter validation fails.

php 8 native functions

Other new features in PHP 8

In addition to all the innovations just described, there are many others just as interesting. One, is the mentioned Just-In-Time (or JIT) compilation, which according to the PHP development team, should improve performance by reducing the compilation time by a third, especially in certain use cases.

In addition, the possibility of using the static keyword as a return type has been introduced. Its use is defined and described extensively in this RFC:

 
class Test
{
  public function test(): static
  {
    return new static();
  }
}

In addition, there are many other new features; the best way to get a comprehensive overview is to take a look at the PHP 8 release notes, which include a long list of examples and links.
 
by Janeth Kent Date: 29-12-2020 php php8 hits : 430  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The most popular Array Sorting Algorithms In PHP

There are many ways to sort an array in PHP, the easiest being to use the sort() function built into PHP. This sort function is quick but has it's limitations,…

MySQL 8.0 is now fully supported in PHP 7.4

MySQL and PHP is a love story that started long time ago. However the love story with MySQL 8.0 was a bit slower to start… but don’t worry it rules…

A roadmap to becoming a web developer in 2019

There are plenty of tutorials online, which won't cost you a cent. If you are sufficiently self-driven and interested, you have no difficulty training yourself. The point to learn coding…

10 PHP code snippets to work with dates

Here we have some set of Useful PHP Snippets, which are useful for PHP Developers. In this tutorial we'll show you the 10 PHP date snippets you can use on…

8 Free PHP Books to Read in Summer 2018

In this article, we've listed 8 free PHP books that can help you to learn new approaches to solving problems and keep your skill up to date.   Practical PHP Testing This book…

Best Websites to Learn Coding Online

You know and we know that it’s totally possible to learn to code for free... If you can teach yourself how to write code, you gain a competitive edge over your…

PHP and XMP format: Create a Panorama 360/VR viewer in PHP and A-Frame

The Extensible Metadata Platform (XMP) is an ISO standard, originally created by Adobe Systems Inc., for the creation, processing and interchange of standardized and custom metadata for digital documents and…

PHP: Basic Introduction to Namespaces

History of PHP Namespaces In PHP prior to 5.3 (2009), any class you define lived at the same global level as other classes. Class User, class Contact, class Db they're all together…

PHP 7.2 will be the first Programming Language to add Modern Cryptography to its Standard Library

Last week, the voting phase closed on an RFC to add libsodium to PHP 7.2. The result was unanimous (37 in favor, 0 against). When version 7.2 releases at the end…

Php: How to extend the highlight_string function

PHP has a cool function that automatically highlights PHP code called highlight_string(); Theoretically this could be used to roll your own code highlighting on a site, rather than rely on…

Install Apache, MariaDB and PHP7 on Ubuntu 16.04

Ubuntu 16.04 LTS Xenial Xerus comes with PHP7 by default so you don’t have to rely on third-party PPA to get PHP7 installed. In this tutorial, we are going to…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration