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

StackOverflow https://stackoverflow.com/questions/12775128

  •  05-07-2021
  •  | 
  •  

Pergunta

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');
Foi útil?

Solução

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.

Outras dicas

Instead of replacing the path with __DIR__, you need to replace the starting apostrophe as well.

E.g. if the path were /foo/bar then you'd want to do this replacement:

"'/foo/bar" to "__DIR__ . '"


Before:

'/foo/bar/configs/template.php'

After:

__DIR__ . '/configs/template.php'

What about write the config directly by:

$data = <<<EOT
return  array('template_dir' => __DIR__ . '/configs/templates.php');
EOT;

file_put_contents($config, $data);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top