I never found a solution to this, but I thought I would post an answer, as I've since decided this isn't a great way to build include paths in the first place.
I came across a much better approach when reading through the Symfony framework (and Composer's generated autoloader):
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitd1d12712f9bc55fdf8d19536f1f9dd88::getLoader();
Here, the PHP magic constant __DIR__
is used as a starting point for the path. From the magic constant manual page:
__DIR__
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent todirname(__FILE__)
. This directory name does not have a trailing slash unless it is the root directory.
There are a number of benefits to this approach:
- It's portable - it will work on any operating system that PHP will run on
- It's flexible/dynamic - you can move your files around and the
__DIR__
constant will reflect the new path without any code changes. - It's familiar - other developers are more likely to recognise this approach, as it uses a native language feature, and they are likely to have come across it before.