Loading...

PHP 8.0 new features

Last updated: Dec 21st 2024

PHP 8.0 contains new features which include named arguments, union types, attributes, constructor property promotion, match expression, nullsafe operator, JIT, and improvements in the type system, error handling, and consistency.  Following is a quick usage of these features.

Named arguments:

htmlspecialchars($string, double_encode: false);

Attributes:

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

Constructor property promotion:

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

Union Types:

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

new Number('NaN'); // TypeError

Match Expressions:

echo match (8.0) {
  '8.0' => "Oh no!",
  8.0 => "This is what I expected",
};
//> This is what I expected

Nullsafe operator:

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

Saner string to number comparisons:

== 'foobar' // false

Consistent type errors for internal functions

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

 

Which new feature do you feel is the best in this new upgrade?

SYED ABDUL QUADER Published on 06 Jan 2021
Edit
Comments
Guest User