Using the PPA ondrej/php it is possible to run multiple PHP version on one system.
All single versions are useable on the CLI, e.g. php7.4 --version
. The command php
will point to the default version.
Now whenever a PHP script is executed by CLI and triggers another PHP script itself, the default version is used.
Example: Your default version is 7.2, you run Composer with 7.4, binaries triggered in hooks still use 7.2.
composer.json
{
"name": "acme/php-cli-switch",
"description": "Test passing different PHP versions to CLI",
"license": "GPL-2.0-or-later",
"scripts": {
"php-version": "php --version"
}
}
Tests
php --version
> PHP 7.2.34
php /usr/local/bin/composer php-version
> PHP 7.2.34
php7.4 --version
> PHP 7.4.22
php7.4 /usr/local/bin/composer php-version
> PHP 7.2.34
Change the default version using update-alternatives
.
sudo update-alternatives --set php /usr/bin/php7.4
sudo update-alternatives --set phar /usr/bin/phar7.4
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.4
Repeat the command whenever the version needs to be changed again.
If it is not allowed to change the default version on the system, then you may override the $PATH
environment variable change the default version.
The important part here is to create a symlink first, which points to the desired version and is named php
exactly. This is due to the fact, that calls for php
are passed to /usr/bin/env
, which looks for an executable named php
in the current $PATH
. It does not work with aliases, shell functions or any other names.
mkdir -p ~/.php/versions/7.4/bin/
ln -s /usr/bin/php7.4 ~/.php/versions/7.4/bin/php
Now pass the version directory as environment variable.
Tests
php --version
> PHP 7.2.34
PATH="/home/$USER/.php/versions/7.4/bin:$PATH" php --version
> PHP 7.4.22
PATH="/home/$USER/.php/versions/7.4/bin:$PATH" php /usr/local/bin/composer php-version
> PHP 7.4.22
Since this is a unpleasantly long command, you may create an alias for it.
.bash_aliases
alias php-cli-7.4='PATH="/home/$USER/.php/versions/7.4/bin:$PATH" php'
Tests
php-cli-7.4 --version
> PHP 7.4.22
php-cli-7.4 /usr/local/bin/composer php-version
> PHP 7.4.22
Longer blog post ✍️ https://pixelbrackets.de/notes/pass-php-version-to-subscripts-in-cli-calls