When working on macOS with PHP, you might need to switch between different PHP versions for various projects. Homebrew offers a convenient way to install and manage multiple PHP versions. In this guide, we’ll walk you through the process of setting up and switching between PHP versions using Homebrew. We’ll also provide you with a handy script to create console aliases for easy PHP version switching.
Prerequisites
Before we begin, ensure you have the following prerequisites in place:
- Homebrew: If you haven’t already installed Homebrew, you can do so by following the instructions on the Homebrew website.
Installing Multiple PHP Versions with Homebrew
Homebrew simplifies the installation and management of multiple PHP versions. To install PHP versions, use the brew install
command followed by the desired PHP version, for example:
brew install [email protected]
brew install [email protected]
You can install as many PHP versions as needed for your projects.
Creating PHP Version Switching Aliases
We’ve also provided a script that adds console aliases for easy PHP version switching. Add the following script to your ~/.bashrc
, ~/.bash_profile
, or ~/.zshrc
file:
# PHP Versions
# Determine versions of PHP installed with HomeBrew
installedPhpVersions=($(brew ls --versions | grep -E 'php(@.*)?\s' | grep -oP '(?<=\s)\d\.\d' | sort -u))
# Create alias for every version of PHP installed with HomeBrew
for phpVersion in ${installedPhpVersions[*]}; do
value="{"
for otherPhpVersion in ${installedPhpVersions[*]}; do
if [ "${otherPhpVersion}" = "${phpVersion}" ]; then
continue
fi
# Unlink other PHP version
value="${value} brew unlink php@${otherPhpVersion} 2>/dev/null;"
done
# Link desired PHP version
value="${value} brew link php@${phpVersion} --force --overwrite 2>/dev/null; } && php -v"
alias "usephp${phpVersion}"="${value}"
done
After adding the script, save the file and run:
source ~/.bashrc # or ~/.bash_profile or ~/.zshrc
Now you can use aliases like usephp8.0
to switch to PHP version 8.0. For example:
usephp8.0
This will activate PHP 8.0 for your current terminal session.
Usage Example
Let’s say you have a project that requires PHP 8.0. You can use the usephp8.0
alias to switch to PHP version 8.0:
usephp8.0
Now, any PHP-related commands you run in this terminal session will use PHP 8.0.
By following this guide and using the provided script, you can seamlessly manage multiple PHP versions for your console on macOS with Homebrew, ensuring compatibility with your various projects. Happy coding!
Leave a Reply