3

我有一个配置文件,它是一个名为 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');
4

3 回答 3

1

除了用 替换路径__DIR__,您还需要替换起始撇号。

例如,如果路径是/foo/bar那么你想要做这个替换:

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


前:

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

后:

__DIR__ . '/configs/template.php'
于 2012-10-08T04:06:40.460 回答
1

这是不可能的,因为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 代码。

于 2012-10-08T04:15:40.077 回答
0

直接通过以下方式编写配置怎么样:

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

file_put_contents($config, $data);
于 2012-10-08T04:14:32.113 回答