PHP 8 New Features: Tutorial

author

By Freecoderteam

Sep 28, 2025

2

image

PHP 8: New Features Tutorial

PHP 8, released on November 26, 2020, is a major update that brings several exciting features and improvements to the language. This tutorial will explore the key features introduced in PHP 8, providing practical examples, best practices, and actionable insights to help you harness the power of this latest version.

Table of Contents


Introduction to PHP 8

PHP 8 is a significant step forward, aiming to enhance developer productivity, improve performance, and introduce modern language features. This version addresses long-standing requests from the PHP community and integrates features inspired by other languages. Let's dive into the key features.


1. Named Arguments

PHP 8 introduces named arguments, allowing developers to pass arguments to functions by their names rather than their positions. This makes code more readable and reduces the risk of errors when dealing with functions that have many parameters.

Example

function connectToDatabase(string $host, int $port, string $username, string $password): void {
    echo "Connecting to database at $host:$port with username $username\n";
}

// Using named arguments
connectToDatabase(
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: 'password123'
);

Benefits

  • Readability: Makes it clear which arguments are being passed.
  • Flexibility: Allows arguments to be passed in any order.
  • Maintainability: Reduces the impact of adding new parameters to functions.

2. Constructor Property Promotion

One of the most popular features in PHP 8 is constructor property promotion, which simplifies the process of initializing object properties. Instead of manually assigning values in the constructor, you can directly declare and initialize properties.

Example

class User {
    // Using constructor property promotion
    public function __construct(
        public string $name,
        public int $age
    ) {
        // No need to assign values here
    }
}

$user = new User(name: 'John Doe', age: 30);
echo $user->name; // Outputs: John Doe

Benefits

  • Simplifies Code: Reduces boilerplate code for property initialization.
  • Consistency: Ensures that properties are always initialized when the object is created.

3. Match Expression

PHP 8 introduces the match expression, a modern alternative to switch statements. It offers a more concise syntax for matching values and executing corresponding code.

Example

function getDayName(int $dayNumber): string {
    return match ($dayNumber) {
        1 => 'Monday',
        2 => 'Tuesday',
        3 => 'Wednesday',
        4 => 'Thursday',
        5 => 'Friday',
        6 => 'Saturday',
        7 => 'Sunday',
        default => 'Invalid day number',
    };
}

echo getDayName(3); // Outputs: Wednesday

Benefits

  • Readability: More concise and expressive than traditional switch statements.
  • Safety: Encourages exhaustiveness and prevents missing cases.

4. Nullsafe Operator

The nullsafe operator (?->) allows you to safely access properties or call methods on objects that might be null, without triggering a fatal error.

Example

class User {
    public ?Address $address;
}

class Address {
    public string $city;
}

$user = new User();
$user->address = new Address();
$user->address->city = 'New York';

// Using nullsafe operator
$city = $user->address?->city;

// If address is null, $city will be null
var_dump($city); // Outputs: string(8) "New York"

$user->address = null;
$city = $user->address?->city;
var_dump($city); // Outputs: NULL

Benefits

  • Safety: Prevents Fatal error: Uncaught Error: Call to a member function city() on null.
  • Simplicity: Reduces the need for explicit null checks.

5. Attributes (Annotations)

PHP 8 introduces attributes, a feature inspired by other languages like Java and C#. Attributes provide a way to attach metadata to classes, methods, or properties, making code more declarative.

Example

#[AllowDynamicProperties]
class Config {
    // This attribute allows dynamic properties
    public function __construct() {
        $this->database = 'mysql';
    }
}

$config = new Config();
$config->host = 'localhost'; // Allowed due to the attribute

Benefits

  • Declarative Code: Makes intent clearer by attaching metadata directly to code elements.
  • Extensibility: Enables frameworks to use custom attributes for configuration or validation.

6. JIT (Just-In-Time) Compiler

PHP 8 introduces an experimental Just-In-Time (JIT) compiler to improve performance. JIT compiles frequently executed code into optimized machine code during runtime, reducing execution time.

How to Enable JIT

php -d zend.assertions=1 -d opcache.jit_buffer_size=64M -d opcache.jit=tracing

Benefits

  • Performance: Significant speed improvements for certain workloads.
  • Future Potential: As JIT matures, it may become a core feature in future releases.

7. Mixed Type

PHP 8 introduces the mixed type, which represents a value that can be of any type. This is useful when a function can return multiple types.

Example

function getValue(): mixed {
    return rand(0, 1) === 1 ? 'string' : 42;
}

$value = getValue();

Benefits

  • Type Hints: Provides a clear way to indicate that a function can return any type.
  • Clarity: Improves code readability by making it explicit that a value can be of any type.

8. Static Return Type

PHP 8 allows functions to return the static keyword as a return type hint. This is particularly useful in classes that extend a base class and want to return the specific subclass type.

Example

class Animal {
    public function speak(): static {
        return $this;
    }
}

class Dog extends Animal {
    public function bark(): void {
        echo "Woof!\n";
    }
}

$animal = new Dog();
$animal->speak()->bark(); // Outputs: Woof!

Benefits

  • Polymorphism: Enables more flexible return types in inheritance hierarchies.
  • Safety: Ensures that the returned object is of the correct type.

Best Practices and Actionable Insights

1. Use Named Arguments for Clarity

When working with complex functions, leveraging named arguments can significantly improve code readability. This is especially useful in library or framework code where function signatures might change.

2. Embrace Constructor Property Promotion

Constructor property promotion can reduce boilerplate code and make your classes more maintainable. However, ensure that all properties are truly required for object initialization.

3. Prefer match Over switch

The match expression is more concise and expressive than the traditional switch statement. It's especially useful for simple cases where you need to map values to specific actions.

4. Use Nullsafe Operator for Safety

The nullsafe operator (?->) is a powerful tool for preventing runtime errors. Use it whenever there's a possibility that an object might be null.

5. Experiment with JIT

While JIT is still experimental, it can provide significant performance gains for certain applications. Test it in your environment to see if it improves performance without introducing bugs.

6. Leverage Attributes for Metadata

Attributes provide a clean way to attach metadata to your code. Use them to simplify configuration and make your code more declarative.

7. Be Mindful of mixed and static

While mixed and static types offer flexibility, use them judiciously. Overusing them can lead to less clear type hints, so reserve them for cases where they provide genuine benefits.


Conclusion

PHP 8 brings a wealth of new features that enhance developer productivity, improve performance, and modernize the language. From named arguments and constructor property promotion to the match expression and nullsafe operator, these features make PHP more expressive and safe. By adopting these best practices and actionable insights, you can take full advantage of PHP 8's capabilities and write cleaner, more maintainable code.

As you migrate to PHP 8, take the time to explore these features and incorporate them into your projects. They not only improve the quality of your code but also position you to take advantage of future PHP releases.

Happy coding! 🎉


References:

Share this post :

Subscribe to Receive Future Updates

Stay informed about our latest updates, services, and special offers. Subscribe now to receive valuable insights and news directly to your inbox.

No spam guaranteed, So please don’t send any spam mail.