Rector PHP: Complete Guide with Examples
Rector is a powerful tool for automated PHP code refactoring. It's a library that analyzes your code using an Abstract Syntax Tree (AST) and applies predefined transformation rules. This automates routine code update tasks like migrating to new PHP versions, adopting new language features, fixing deprecated constructs, and improving overall code quality.
Why use Rector? In modern PHP development, projects grow quickly, and keeping them up-to-date becomes increasingly challenging. Manually refactoring thousands of lines of code is time-consuming and error-prone. Rector solves this by performing complex transformations in seconds. It's especially useful when upgrading from PHP 7.x to 8.x, migrating from legacy frameworks (e.g., Zend Framework 1 to Laminas), or implementing strict types and modern patterns.
Rector operates on a "rule set" principle. You define which transformations to apply (e.g., "replace all array_* calls with str_* functions"), and Rector finds all matching locations in your code and makes the changes. The tool is fully customizable: you can use community-ready rule sets or create your own. Rector integrates into CI/CD pipelines, allowing automatic code checking and fixing with every commit.
Installation
Rector is installed via Composer, the standard PHP package manager. Run the following command in your project root:
composer require rector/rector --dev
The --dev flag installs the package only for development, which is best practice since Rector isn't needed in production.
After installation, verify everything works:
vendor/bin/rector --version
For a global installation (not recommended for projects), you can run:
composer global require rector/rector
Rector requires PHP 7.2 or higher. PHP 8.0+ is recommended for maximum performance and full feature support.
Quick Start: Minimal Working Example
Let's create a simple PHP file that needs refactoring. Suppose we have legacy code using create_function(), which was removed in PHP 8.0.
Step 1. Create example.php:
<?php
$oldFunction = create_function('$a, $b', 'return $a + $b;');
echo $oldFunction(1, 2); // Outputs 3
Step 2. Create a config file rector.php in your project root:
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Function_\CreateFunctionToAnonymousFunctionRector;
return static function (RectorConfig $rectorConfig): void {
// Specify which directories to analyze
$rectorConfig->paths([
__DIR__ . '/example.php',
]);
// Register the rule to replace create_function with anonymous functions
$rectorConfig->rule(CreateFunctionToAnonymousFunctionRector::class);
};
Step 3. Run Rector:
vendor/bin/rector process --dry-run
The --dry-run flag shows what changes will be made without applying them. To actually modify files, run:
vendor/bin/rector process
Result: The example.php file will be transformed to:
<?php
$oldFunction = function ($a, $b) {
return $a +