PHP has no way of knowing what the "root of the project" is. You could have any number of directories on your disk, with files called vendor/autoload.php
in several of them, and only you know what's special about the "project root". So ultimately, the answer is no, there is no way.
However, note that you only need to include the autoloader in files which aren't themselves included or autoloaded. The autoloader is something you load once, as part of the configuration / bootstrapping of your code, and it then loads whatever classes it needs wherever they're referenced.
So the way to limit the mess of different levels is to structure your project carefully. For instance:
- Route all requests via one or two "routers", such as a single "index.php" file. Use Apache mod_rewrite or the equivalent in Nginx etc to make all URLs actually load this script, and then in the script work out what code to run based on the URL. You can use libraries such as nikic/FastRoute to translate the URLs into functions to call, which will then be autoloaded.
- Use different PHP files, but all in a reasonably flat directory structure, so that they all have to "climb" the same number of levels to reach the project root.
The same principle applies to use in command-line scripts or any other kind of application: limit or structure the "entry points", because only those need to know where to load the autoloader.
If you already have some kind of config file loaded on every request / script run / unit test / etc, it might be sensible to put the require_once 'vendor/autoload.php';
line in there. Like the configuration, the autoloader is "global state" that you want to just set up once and then forget about.