Something About PHP 8 Released

History of PHP

PHP wasn’t always awesome like it is today. Back in the days, it was all messy and didn’t compare at all with strongly typed languages but it was versatile enough to domain the web. Other languages rise and threaten the PHP domain in web application development. Right before PHP 7, many people believed that PHP was dead by now.

PHP 7 appears and changes everything making a huge performance improvement and introducing types and other features. Now it’s time for PHP 8 to grow and continue the PHP legacy.

PHP 8 is a major upgrade to the popular dynamic language for server-side web programming, is now available as a production release, featuring union types, named arguments, attributes, and Just-In-Time compilation.

What are the new shine features in PHP 8?

Named arguments

Now you have named arguments that allow you to specify only the required arguments and skip the optional ones. This way arguments are also order-independent and self-documented. Here is an example of the htmlspecialchars function that has some optional arguments:

# htmlspecialchars signature
htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get(“default_charset”) [, bool $double_encode = TRUE ]]] ) : string

# you can call it like this
htmlspecialchars($string, double_encode: false);

Attributes

Use structured data with PHP’s native syntax instead of PHPDoc annotations. It goes like this:

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

Constructor property promotion

A cleaner way to define and initialize properties. More succinctly, with less code but still readable you can setup class properties by passing the variables, with the same name, by argument to the constructor. Se the example below:

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

# instead of this
class Point {
  public float $x;
  public float $y;
  public float $z;

  public function __construct(
    float $x = 0.0,
    float $y = 0.0,
    float $z = 0.0,
  ) {
    $this->x = $x;
    $this->y = $y;
    $this->z = $z;
  }
}

Union types

With PHP 7 you could combine types with PHPDoc. Now PHP 8 supports it natively. I personally think this new feature is very helpful because I don’t like PHPDoc because, in my opinion, makes the code more difficult to read. Here’s how it goes:

public function __construct(
    private int|float $number
  ) {}
}

new Number(‘NaN’); // TypeError

Match expression

A match expression capability is added, similar to switch but with safer semantics and the ability to return values.

It is an expression so you can store it in a variable or return it. Only supports single-line expressions and there is no need for a break; statement. This on I am not still sure of any real use that I can give but I am sure that it will be useful sometime in the future:

echo match (8.0) {
  ‘8.0’ => “Oh no!”,
  8.0 => “This is what I expected”,
};
//> This is what I expected

Nullsafe operator

With this, you no longer need to verify each element in a chain of calls. When the evaluation of one element fails, the executions of the entire chain is aborted and evaluates to null. Now there is no need to check if the element of the chain exists:

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

Saner string to number comparisons

When comparing to a numeric string, PHP 8 uses a number comparison. Otherwise, it converts the number to a string and uses a string comparison.

# PHP 7
0 == ‘foobar’ // true

# PHP 8
0 == ‘foobar’ // false

 

Consistent type errors for internal functions

Most of the internal functions now throw an Error exception if the validation of the parameters fails.

# PHP 7
strlen([]); // Warning: strlen() expects parameter 1 to be string, array given

array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0

# PHP 8
strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given

array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0

 

And much more

The performance and error handling also were improved and the results look promising. I can’t wait to put my hands in it.

PHP is becoming better and better as its ages. There is much more in PHP 8 that I need to test and find how it will be useful in the real world. But from what I already see, it looks promising and makes me proud that I work with PHP.