我有一个配置文件,它是一个名为 config.php 的 php 数组。
return array(
'template_dir' => __DIR__ '/configs/templates.php'
)
然后,每当我想使用这个配置文件时,我就只包含 config.php。通过这种方式编写配置文件也非常容易。
file_put_contents($config, 'return ' . var_export($data, true));
但我希望能够将魔术常量 DIR 写入配置文件而不扩展它。到目前为止,我还没有想出一种方法来做到这一点。我已尝试一切编写 recursiveArrayReplace 方法来删除整个路径并尝试将其替换为
__DIR__
但它总是出现
'__DIR__ . /configs/template.php'
在这种情况下,运行时不会扩展。
怎么写
__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');
最佳答案
这是不可能的,因为 var_export()
打印变量,而不是表达式。
最好将所有路径写为相对目录,并在获取数据后规范化为完整的工作路径。
您还可以考虑返回一个对象:
class Config
{
private $paths = array(
'image_path' => '/configs/template.php',
);
public function __get($key)
{
return __DIR__ . $this->paths[$key];
}
}
return new Config;
或者,您必须自己生成 PHP 代码。
关于php - 如何在不评估或扩展魔术常量 __DIR__ 的情况下编写或打开 php 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775128/