Getting Started with PHP 8.3
Learn the latest features and syntax improvements in PHP 8.3 with hands-on examples.
Getting Started with PHP 8.3
PHP 8.3 brings exciting new features and improvements that make the language more powerful and developer-friendly. In this comprehensive tutorial, we'll explore the key additions and how to use them in your projects.
What's New in PHP 8.3?
1. Typed Class Constants
One of the most anticipated features is the ability to add type declarations to class constants:
1class Status {
2 public const string PENDING = 'pending';
3 public const string APPROVED = 'approved';
4 public const string REJECTED = 'rejected';
5}This provides better type safety and makes your code more self-documenting.
2. Dynamic Class Constant Fetch
You can now fetch class constants dynamically using variables:
1class Config {
2 public const string APP_NAME = 'MyApp';
3 public const string APP_VERSION = '1.0.0';
4}
5
6$constantName = 'APP_NAME';
7echo Config::{$constantName}; // Outputs: MyApp3. #[Override] Attribute
The new #[Override] attribute helps prevent bugs by ensuring a method actually overrides a parent method:
1class ParentClass {
2 public function process(): void {
3 // Implementation
4 }
5}
6
7class ChildClass extends ParentClass {
8 #[Override]
9 public function process(): void {
10 // This will work fine
11 }
12}Setting Up PHP 8.3
Installation on Ubuntu/Debian
1sudo add-apt-repository ppa:ondrej/php
2sudo apt update
3sudo apt install php8.3Installation on macOS
1brew install php@8.3
2brew link php@8.3Practical Example: Building a User Service
1<?php
2declare(strict_types=1);
3
4namespace App\Services;
5
6enum UserStatus: string {
7 case ACTIVE = 'active';
8 case INACTIVE = 'inactive';
9 case SUSPENDED = 'suspended';
10}
11
12class UserService {
13 public const string DEFAULT_ROLE = 'user';
14
15 public function __construct(
16 private readonly Database $db
17 ) {}
18
19 public function create(array $data): User {
20 $user = new User(
21 email: $data['email'],
22 name: $data['name'],
23 status: UserStatus::ACTIVE,
24 role: self::DEFAULT_ROLE
25 );
26
27 $this->db->save($user);
28 return $user;
29 }
30}Conclusion
PHP 8.3 continues the language's evolution toward better type safety, developer experience, and performance. Start experimenting with these features in your projects today!