PHP include_once:处理导入,即配置文件 [英] PHP include_once: handling of imports i.e. for configuration files

查看:971
本文介绍了PHP include_once:处理导入,即配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下结构:

index.php
config.inc.php
\ lib
\ lib \ common.php

数据库名称等几个参数,用户& co在 config.inc.php 中配置。访问它们的正确方法是什么,即从位于 \lib\common.php 中的函数。我真的必须在每个函数中执行 include_once(config.inc.php)吗?

Several parameters like database name, user & co are configured in config.inc.php. What is the proper way to access them i.e. from a function located in \lib\common.php. Do I really have to do an include_once("config.inc.php") within each function there?

如果出现以下情况似乎无效:

It doesn't seem to work if:


  • config.inc.php 是在index.php中包含一次,包括 \lib\common.php 那里

  • 如果 config.inc.php 在包含 \lib\common.php 和所有其他文件之前定义所有变量(这样我只需要在 index.php
  • $的所有中央文件中包含 config.inc.php b $ b
  • 如果 config.inc.php 包含在 \lib\common.php <的顶部,它也不起作用/ code>

  • config.inc.php is included once once in index.php, before including \lib\common.php there
  • if config.inc.php defines all variables before including \lib\common.php and all other files (this way I would only have to include config.inc.php in all "central" files at the level of index.php
  • neither does it work if config.inc.php is included at the top of \lib\common.php

非常感谢 - 我无法找到Google的解决方案!

Many thanks - I wasn't able to find a solution with Google!

解决方案

我包括 config.inc.php 一次在 index.php (由Galen建议)并使用全局(如David所建议)。一切都很好国王正如我所料,非常感谢!

I included config.inc.php once in index.php (as suggested by Galen) and used global (as suggested by David). Everything is working as I would expect it, many thanks!

稍后我肯定会按照n3rd的建议调查 auto_prepend ,tkx也是如此!

Later on I will definitely look into auto_prepend as suggested by n3rd, tkx for that as well!

推荐答案

你必须使用 global 关键字,用于访问在函数外定义的变量:

You have to use the global keyword to access variables which were defined outside of a function:

$var1 = "muh";
$var2 = "foo";

function test() {
    global $var1;
    echo "var1=$var1; var2=$var2\n";
}

将打印var1 = muh; var2 =

这篇关于PHP include_once:处理导入,即配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆