phpstringmagic-constants

How to write or open a php array without evaluating or expanding magic constant __DIR__


I have a config file that is a php array named config.php.

return array(
    'template_dir' => __DIR__ '/configs/templates.php'
)

Then whenever I want to use this config file I would just include config.php. Its also really easy to write a config file in this way.

file_put_contents($config, 'return ' . var_export($data, true));

But I would like to be able to write the magic constant DIR to the config file without it expanding. So far I have not been able to come up with a way to do this. I have tried everything to writing a recursiveArrayReplace method to remove the entire path and trying to replace it with

    __DIR__

but it always comes up as

    '__DIR__ . /configs/template.php'

Which in that case will not expand when its ran.

How can I write

   __DIR__ to an array in a file or how ever else without the quotes so that it looks like,

array('template_dir' => __DIR__ . '/configs/templates.php');

Solution

  • This is not possible, because var_export() prints variables, not expressions.

    It would be better to write all your paths as relative directories instead and canonicalize to a full working path after fetching the data.

    You could also consider returning an object:

    class Config
    {
        private $paths = array(
            'image_path' => '/configs/template.php',
        );
    
        public function __get($key)
        {
            return __DIR__ . $this->paths[$key];
        }
    }
    
    return new Config;
    

    Alternatively, you'd have to generate the PHP code yourself.