What's new in PHP 8.2

  • October 11, 2023
  • 241

Các tính năng mới cần biết khi sử dụng php 8.2. 

Constructor property promotion

Định nghĩa và khởi tạo các thuộc tính cho đối tượng ngắn hơn.


# PHP 7
class Point {
  public float $x;

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

# PHP 8
class Point {
  public function __construct(
    public float $x = 0.0
  ) {
  }
}

Union types

Ép kiểu đối số truyền vào.


# PHP 7
class Number {
  /** @var int|float */
  private $number;

  /**
   * @param float|int $number
   */
  public function __construct($number) {
    $this->number = $number;
  }
}

new Number('NaN'); // Ok

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

new Number('NaN'); // TypeError

Match expression

Sử dụng match() expression là cách viết cực kì ngắn ngọn thay cho switch case


# PHP 7
switch (8.0) {
  case '8.0':
    $result = "Oh no!";
    break;
  case 8.0:
    $result = "This is what I expected";
    break;
}
echo $result;
//> Oh no!

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

Nullsafe operator

Kiển tra null theo cách mới cú pháp giống javascript


# PHP 7
$country =  null;
if ($session !== null) {
  $user = $session->user;
  if ($user !== null) {
    $address = $user->getAddress();
    if ($address !== null) {
      $country = $address->country;
    }
  }
}

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

Nullability

Khai báo param null cho function


class Test {
    // Error: Using null default on non-nullable property
    public function __construct(public Type $prop = null) {}

    // Correct: Make the type explicitly nullable instead
    public function __construct(public ?Type $prop = null) {}
}

Readonly classes

Cho phép khai báo class readonly


# Before
class Post
{
    public function __construct(
        public readonly string $title, 
        public readonly Author $author,
        public readonly string $body,
        public readonly DateTime $publishedAt,
    ) {}
}

# After
readonly class Post
{
    public function __construct(
        public string $title, 
        public Author $author,
        public string $body,
        public DateTime $publishedAt,
    ) {}
}

Disjunctive Normal Form (DNF) Types

Kiển tra đối số truyền vào bằng cách khai báo DNF type


# PHP < 8.2
class Foo {
    public function bar(mixed $entity) {
        if ((($entity instanceof A) && ($entity instanceof B)) || ($entity === null)) {
            return $entity;
        }

        throw new Exception('Invalid entity');
    }
}

# PHP 8.2
class Foo {
    public function bar((A&B)|null $entity) {
        return $entity;
    }
}

Constants in traits

Có thể khai báo biến constant trong traist. Lớp sử dụng traist sẽ gọi được các biến trong traist, không thể gọi biến constant trực tiếp từ traist


trait Foo
{
    public const CONSTANT = 1;
}

class Bar
{
    use Foo;
}

var_dump(Bar::CONSTANT); // 1
var_dump(Foo::CONSTANT); // Error

Deprecate dynamic properties

Bỏ tính năng dynamic properties của đối tượng


PHP < 8.2
class User
{
    public $name;
}

$user = new User();
$user->last_name = 'Doe';

$user = new stdClass();
$user->last_name = 'Doe';

// PHP 8.2
class User
{
    public $name;
}

$user = new User();
$user->last_name = 'Doe'; // Deprecated notice

$user = new stdClass();
$user->last_name = 'Doe'; // Still allowed

Redact parameters in back traces

Không hiển thị các đối số nhạy cảm khi hàm xảy ra lỗi


# PHP < 8.2
function encryptPassword(string $password): string {
    throw new Exception('Error');
}

encryptPassword('pwd123');

// Khi có lỗi xảy ra output trả về làm lộ thông tin mật khẩu
Fatal error: Uncaught Exception: Error in main.php:4
Stack trace:
#0 main.php(7): encryptPassword('pwd123')
#1 {main}
  thrown in main.php on line 4

# PHP 8.2
function encryptPassword(#[\SensitiveParameter] string $password): string {
    throw new Exception('Error');
}
encryptPassword('pwd123');

// Khi có lỗi xảy ra output trả về ẩn thông tin mật khẩu
Fatal error: Uncaught Exception: Error in main.php:4
Stack trace:
#0 main.php(7): encryptPassword(Object(SensitiveParameterValue))
#1 {main}
  thrown in main.php on line 4

Enum

Hỗ trợ enum từ php 8.1

enum Status: string  implements HasColor
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';
    
    public function color(): string
    {
        return match($this) 
        {
            Status::DRAFT => 'grey',   
            Status::PUBLISHED => 'green',   
            Status::ARCHIVED => 'red',   
        };
    }
}

interface HasColor
{
    public function color(): string;
}

$status = Status::ARCHIVED;

$status->color(); // 'red'
Readonly Properties
Hỗ trợ thuộc tính readonly từ php 8.1
class BlogData
{
    public readonly Status $status;
   
    public function __construct(Status $status) 
    {
        $this->status = $status;
    }
}

Tổng kết

Trên đây là các tính năng mới hay ho của php 8, 8.1, 8.2. Các bạn hãy áp dụng vào dự án của mình nhé. Thank for reading...