我有一个配置文件,它是一个名为config.php的php数组。
return array(
'template_dir' => __DIR__ '/configs/templates.php'
)
然后每当我想使用此配置文件时,我只会包含 config.php。 以这种方式编写配置文件也非常容易。
file_put_contents($config, 'return ' . var_export($data, true));
但是我希望能够在不扩展的情况下将魔术常量DIR写入配置文件。 到目前为止,我还没有想出一种方法来做到这一点。 我已经尝试了一切来编写递归数组替换方法来删除整个路径并尝试将其替换为
__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代码。
不是用 __DIR__
替换路径,你还需要替换起始撇号。
例如,如果路径/foo/bar
,那么您需要执行此替换:
"'/foo/bar"
到"__DIR__ . '"
以前:
'/foo/bar/configs/template.php'
后:
__DIR__ . '/configs/template.php'
直接通过以下方式编写配置怎么样:
$data = <<<EOT
return array('template_dir' => __DIR__ . '/configs/templates.php');
EOT;
file_put_contents($config, $data);