The smallest PHP version switcher

PHP is becoming more and more feature-rich, so we recommend using a recent, stable version such as PHP 8.1 in your projects.

However, you might have to support projects built on older versions of PHP. This can lead to incompatibilities and impair your ability to run the project locally.

Tools like Docker and Homestead are good solutions to this problem, but in this post I will show a really lightweight way of working around this.

Here we go:

👉 Step 1: install multiple versions of PHP using Homebrew:

brew install php@7.4
brew install php@8.0
brew install php@8.1

👉 Step 2: add aliases to your shell for enabling the various versions:

alias php7="brew unlink php@8.0 php@8.1 && brew link php@7.4"
alias php8="brew unlink php@8.1 php@7.4 && brew link php@8.0"
alias php81="brew unlink php@8.0 php@7.4 && brew link php@8.1"

That’s it! Done.

Run php8 to switch to PHP 8, run php7 to switch to PHP 7.4, et cetera. Tweak the script to match your version requirements and preferences.

Do remember to unlink all other versions in your aliases, to avoid conflicts.

Composer version constraints

Oh! One last thing.

Now that your PHP versions depends on whatever you switched to last, it’s a matter of time before you will realize you ran a command using the wrong PHP version. Oops.

It helps to add a version constraint to your composer.json. This will warn you when you’re running composer install using the wrong version.

You can add this to your require block. Here’s an example:

"require": {
    "php": "~8.1",
}

With this safeguard in place, you’re good to go.

Thanks to Martijn for this handy solution. 🙌


We welcome your feedback

We enjoy compliments, but you can totally shout at us for doing it wrong on our Twitter account 👋