Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Upgrade your PHP code to use PHP 8.2 features using Rector

In this post, I’ll show you how to upgrade your PHP code to use PHP 8.2 features using Rector. I have written articles about how to upgrade to PHP 8 and PHP 8.1 previously.

Since PHP 8.2 is an incremental upgrade to PHP 8 and PHP 8.1, it’s important that you upgrade your code in that sequence first.

Once that is done, follow this guide to upgrade it to PHP 8.2 further.

Configuring Rector

First install and configure Rector as a development dependency in your project.

Next, as I mentioned in that article, Rector uses something called rules to upgrade the PHP codebase.

<?php

declare(strict_types=1);

use Rector\Php82\Rector\Class_\ReadOnlyClassRector;
use Rector\Php82\Rector\FuncCall\Utf8DecodeEncodeToMbConvertEncodingRector

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $services = $containerConfigurator->services();

    $services->set(ReadOnlyClassRector::class);

    $services->set(Utf8DecodeEncodeToMbConvertEncodingRector::class);
};

Upgrading to PHP 8.2

Once the required configuration is done, you’re ready to start upgrading to PHP 8.2.

Next, you’ll need to run the following command to apply all the PHP 8.2 related changes. To see what changes would be applied, we can run this command with the --dry-run option like so.

$ vendor/bin/rector process src --dry-run

Here src is the folder that you want to be analyzed by Rector. Once run, the command will show diff and all the rules it used.

If you’re satisfied with the potential changes, you can finally apply all changes in real by dropping --dry-run from the previous command and running it like so.

$ vendor/bin/rector process src

And that’s how you can upgrade about any codebase to PHP 8.2. Just like that!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?