Most of us works on multiple projects of sub-products in the same time, so in this article I will cover how to install multiple PHP versions and how to switch between them.
For PHP developers they may be using frameworks that require using a specific version of PHP, frameworks like Laravel have this issue as they do not focus on backward compatibility with old PHP versions, this can be a good practice to force you update your code.
1. Prerequisites
You’ll need both Xcode Command Line Tools and Homebrew installed.
1.1 Install XCode Command Line Tools
xcode-select --install
1.2 Install Homebrew
Homebrew is a package manager for macOS. It’s like apt on Ubuntu.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Check that brew has installed:
$ brew --version Homebrew 2.2.5
You can also run brew doctor to check everything is good to go.
1.3 Required Libraries
When installing fresh, I found a few required libraries that were missing when completing all the steps below. To make things easier, please simply run this now:
2. Install Multiple PHP Versions
Up until the end of March 2018, all PHP related brews were handled by Homebrew/php tab, but that has been deprecated, so now we use what's available in the Homebrew/core package. This should be a better maintained, but is a much less complete, set of packages.
PHP 7.0, PHP 7.1, PHP 7.2, PHP 7.3, and PHP 7.4 have been deprecated and removed from Brew because they are out of support, and while it's not recommended for production, there are legitimate reasons to test these unsupported versions in a development environment. These versions also need to "built from source" in order to use the latest versions of icu4c and openssl.
Only PHP 8.0 through 8.1 are officially supported by Brew, but these also have to be built which is pretty slow. For the latest version of our guide we will use the new tap from @shivammahtur as there are many versions (including the latest PHP 8.2) pre-built.
We will proceed by installing various versions of PHP and using a simple script to switch between them as we need. Feel free to exclude any versions you don't want to install.
Also, you may have the need to tweak configuration settings of PHP to your needs. A common thing to change is the memory settings or the date.timezone configuration. The php.ini files for each version of PHP are located in the following directories:
To continue, I strongly recommend closing ALL your terminal tabs and windows.
This will mean opening a new terminal to continue with the next step. This is strongly recommended because some really strange path issues can arise with existing terminals.
Now I have installed but not linked these PHP versions. To switch to PHP 7.3 for example we can type:
Quick test that we're in the correct version:
and to switch to to 8.2:
And check that it's changed correctly:
Now you can use multiple PHP versions on MacOS.