Everyday Efficiency: PHP 8 Techniques for WordPress Engineers

As a software engineer navigating the daily challenges of WordPress development, embracing the latest tools and tricks is essential to staying efficient and effective. In this post, I want to share three PHP 8 tricks I incorporate into my everyday tasks as a software engineer working on WordPress projects.

When PHP 8.0 was released, I wrote about my favourite improvements here, and you’ll see some of them in this post – however, this time those techniques are part of my day as an engineer.

These tricks aren’t just about staying up-to-date; they’re practical enhancements that make my coding life easier and my WordPress development more streamlined. Let’s dive in!

Easier Null Handling with “?->” Operator


In PHP 8, there’s a cool trick called the Nullsafe Operator (?->). It helps when you’re dealing with nested objects and saves you from writing lots of null-checks. Check out this example:

// classic one
if ($user !== null && $user->getProfile() !== null) {
   $avatar = $user->getProfile()->getAvatar();
} else {
   $avatar = 'default.jpg';
}
// With PHP 8 Nullsafe Operator
$avatar = $user?->getProfile()?->getAvatar() ?? 'default.jpg';

This makes your code shorter and easier to read, especially when working with WordPress objects.

Cleaner Conditionals with “match” Instead of “switch”


PHP 8 has a new way to handle conditions using the match expression. It’s like the old switch statement but more concise. Look at this:


// Traditional switch
switch ($status) {
case 'published':
   $message = 'Post is live!';
   break;
case 'draft':
   $message = 'Post is still in draft.';
   break;
default:
   $message = 'Post status unknown.';
}
// PHP 8 match expression
$message = match( $status ) {
   'published' => 'Post is live!',
   'draft'     => 'Post is still in draft.',
   'default'   => 'Post status unknown.',
};

Personally, I love this one! When you avoid overusing If/else statements in your code, matching labels with indexes is always a great solution – even better when you can match the index with the actual status.

Constructor Property Promotion for Cleaner Class Definitions:

PHP 8 introduces a streamlined way to define classes with the Constructor Property Promotion feature. This feature is a game-changer for WordPress developers, allowing for more concise and readable class definitions. It’s particularly useful when creating custom components like widgets or API responses. Instead of declaring class properties and then assigning them in the constructor, PHP 8 allows you to do both simultaneously, thereby reducing boilerplate code.

For example, consider a custom widget in a WordPress theme:

// PHP 7 style
class CustomWidget {
    private $title;
    private $content;

    public function __construct($title, $content) {
        $this->title = $title;
        $this->content = $content;
    }
}

// PHP 8 Constructor Property Promotion
class CustomWidget {
    public function __construct(
        private $title, 
        private $content
    ) {}
}

This approach makes the code significantly more concise and enhances readability, which is essential in complex WordPress projects.

Named Arguments for More Readable Function Calls

PHP 8’s Named Arguments feature significantly enhances the readability of function calls, especially in WordPress where functions often come with multiple parameters. This feature allows developers to pass arguments to a function based on their names, rather than their position, making the code more understandable and less prone to errors related to the ordering of arguments.

Again, considering a WordPress function call scenario:

// PHP 7 positional arguments
add_theme_support('custom-background', array(
    'default-color' => '000000',
    'default-image' => '',
));

// PHP 8 named arguments
add_theme_support('custom-background', default-color: '000000', default-image: '');

// Another example with WP_Query
$query = new WP_Query(array(
    'post_type' => 'post',
    'posts_per_page' => 10,
    'orderby' => 'title',
    'order' => 'ASC'
));

// With PHP 8 named arguments
$query = new WP_Query(
    post_type: 'post',
    posts_per_page: 10,
    orderby: 'title',
    order: 'ASC'
);

Using named arguments not only clarifies the purpose of each parameter but also makes the code more flexible for future changes, an invaluable asset in the evolving landscape of WordPress development.

More Control with Union Types

PHP 8 introduces something called union types. It’s a way to say a variable can be one of several types. This is handy when working with functions that can take different kinds of data:


// Without union types
function processUserData($data) {
// Function logic here
}
// With union types
function processUserData( array|string $data ) {
// Function logic here
}


By using union types, you can be clearer about what kind of data your functions expect, making your WordPress code more robust.

Is WordPress core already prepared for PHP 8?

It’s very important that you run your local PHP environment as similar as possible to your project’s final server, because although WP core is compatible with PHP, you’ll see that officially the stable version continues to be 7.4. But my advice: run at least version 8.1 🙂

Conclusion

These PHP 8 tricks might seem small, but they can make a big difference in your WordPress development. The Nullsafe Operator, Match Expression, and Union Types are easy to understand and implement. By using these tricks, you’ll not only stay current but also write code that’s simpler, cleaner, and more effective in your WordPress projects.

All these details will reveal that you’re proud of your work. In a world where >40% of the Internet potentially can run your code, keep in mind you have the mission to create a web that is being designed to last.


Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *