TUTORIAL

Getting Started with Modern PHP Features

By Bryan Chung | Published on November 05, 2024

Quick Summary

PHP 8.0+ introduces strict typing and modern syntax that matches other enterprise languages.

  • - Typed Properties: Enforce data integrity in classes.
  • - Constructor Promotion: Reduce boilerplate code.
  • - Attributes: Native metadata (replacing PHPDoc annotations).
  • - Match Expression: Strict, return-value based alternative to switch.

PHP has evolved significantly over the last decade. With PHP 8.0, 8.1, and 8.2, the language has introduced powerful typing, performance improvements, and syntax enhancements that make it comparable to other strictly typed languages.

This guide covers essential features you should be using in your new projects.

1. Typed Properties (PHP 7.4+)

Defining types for class properties enforces data integrity and reduces the need for manual type checking methods.

class User {
    public int $id;
    public string $name;

    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

2. Constructor Property Promotion (PHP 8.0)

To reduce boilerplate code, you can declare and initialize properties directly in the constructor signature.

class User {
    public function __construct(
        public int $id, 
        public string $name,
    ) {}
}

3. Attributes (PHP 8.0)

Attributes, also known as annotations in other languages, provide a way to add metadata to classes, methods, and properties. Frameworks like Symfony and Laravel use these extensively for routing and validation.

#[Route('/api/users', methods: ['GET'])]
public function index(): Response {
    // ...
}

4. Match Expression (PHP 8.0)

The `match` expression is a more concise and stricter version of `switch`. It returns a value, does not require `break`, and uses strict comparison.

$status_message = match ($status) {
    '200' => 'OK',
    '400', '404' => 'Client Error',
    '500' => 'Server Error',
    default => 'Unknown Status',
};

Conclusion

Adopting these modern features leads to cleaner, more maintainable, and performant code. If you are starting a new project today, ensure your environment is running the latest stable PHP version to take advantage of these improvements.

Upgrade Your Legacy PHP App

We help businesses modernize their codebase, improve security, and implement the latest PHP standards.

View our Custom Development Services ->

About the Author

Bryan Chung is a full-stack developer and digital strategist. He advocates for modern PHP practices and robust application architecture.