phpphp-8.2

How to terminate PHP script due to unsupported PHP version?


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).


Solution

  • 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:

    <?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();
    }
    
    require __DIR__ . "/vendor/autoload.php";
    startMeUp($args);
    

    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.