skip to Main Content

Here is my problem: I have upgraded a complex application to PHP 7.4, and yes, I didn’t test thoroughly enough.

Now I would like to run on task with an older PHP version, but it cannot parse all of my vendor files. Here is the error and the line. It’s a new feature of PHP 7.4.

PHP Parse error: syntax error, unexpected ‘?’, expecting variable (T_VARIABLE) in .vendorsentrysentrysrcfunctions.php on line 25

 function captureMessage(string $message, ?Severity $level = null): ?string

Until now I thought, that Composers vendorautoload.php loads classes and functions in the vendor directory only on demand. Unused classes and therefore the offending files written in PHP 7.4 would not be loaded.

Unfortunately, I notice, that require_once('./vendor/autoload.php') is enough to see the parse error. Is it possible to configure Composer in a way, that it does not preload the vendor files, but loads them only once the classes or functions are requested ?

2

Answers


  1. In your composer.json, you can add platform into your config, to force it to resolve dependencies to a specific version of PHP.

    https://getcomposer.org/doc/06-config.md#platform

    "config": {
        "platform": {
            "php": "5.6"
        },
    },
    
    Login or Signup to reply.
  2. Your original assumption was correct: in general, the PHP autoloader only loads classes when they are used, and Composer simply provides an implementation of that autoloader.

    However, Composer also includes a feature to unconditionally load a file. This is used when a package contains functions, constants, or configuration, which cannot be loaded on-demand (because PHP’s autoloader only handles classes).

    One of the packages you are using uses this feature, so every time you include vendor/autoload.php, the file it specifies is required. In the error message shown, we can see the package name sentry/sentry, and in that package’s composer.json, we can see this:

    "autoload": {
        "files": [
            "src/functions.php"
        ],
        "psr-4": {
            "Sentry\": "src/"
        }
    },
    

    The best way around this is probably to downgrade this dependency, and any others which include code that only runs under PHP 7.4. To do this, you can simply re-run composer update on your older version of PHP, and it will only pick up packages which support that version.

    You can also specify the platform option in your composer.json to always request dependencies for an older PHP version, even when you are running Composer under PHP 7.4. However, there is a risk that the resulting dependencies will be incompatible with PHP 7.4.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search