Does anyone know how to terminate PHP script with too low unsupported version before an error occurs in the same script (due to calling an unsupported function/feature)?
Heres an example with readonly class
which was introduced in PHP 8.2:
#!/usr/bin/env php
<?php
define("MIN_PHP_VER", 8.2);
if (version_compare(PHP_VERSION, MIN_PHP_VER, '<'))
{
echo "This script requires at least PHP " . MIN_PHP_VER . "n";
die();
}
readonly class SomeClass
{
}
This won’t work, obviously, because the entire script is read at the beginning, so in PHP < 8.2 it will thrown an error:
syntax error, unexpected token "readonly"
I would like to make the script execution dependent on the PHP version available in a given environment without having to check it with another script (everything is executed within one script), so expected output should be:
This script requires at least PHP 8.2
Is it somehow possible to achieve?
I know that I can use composer
or two scripts (the first one will execute second one when PHP_VERSION match requirements). But I just want to have one script that will verbose explains to the user why he can’t use it (or it will just execute if the PHP version is right).
2
Answers
PSR1, which is expanded by both PSR-2 and PSR-12, dictates you can have a file declare new symbols, like function and classes, or you can have one with side effects. You should not have a file that does both. Your script does both!
You should do this:
So now you have more than one file, but there is a solution to make it one executable phar archive. Eg.
composer
is an example of an application that is made like that.The typical way to handle this issue would be to use Composer’s
require
configuration to constrain the version at install time. This implies the use of PSR-4 naming conventions, to enable the use of an autoloader — which you should be doing anyway. Given that, you can then just specify your version requirements in thecomposer.json
file, and you won’t need to do any explicit version checking anywhere in your code:Then when you run
composer install
orcomposer update
, you’ll get an error: