【发布时间】:2019-08-31 10:22:09
【问题描述】:
这不是这个Passing a variable from one php include file to another: global vs. not的重复
我正在尝试制作一个简单的 php 项目,其中我有不同的数据库连接文件(config.php)、数据库函数(db_functions.php)、普通函数(functions.php)和索引文件(index.php)。
我在 config.php 中设置了数据库连接 -
$link = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_error());
此连接工作正常(在 index.php 上测试)。 DB_HOST 和其他常量在 config.php 文件中声明。现在,我的 php 文件是这样连接的 -
functions.php 在 index.php 中是必需的(使用 require)
在functions.php中需要db_functions.php(使用require)
db_functions.php 中需要config.php(使用require)
现在,如果我想在 db_functions.php 中使用 $link 变量,它就不起作用了。显示通知Undefined variable: link in db_functions.php on line 10。
我在 db_functions.php 上的函数中调用 $link 在 db_functions.php 上声明 global $link 一次也不起作用。我必须在 db_functions.php 的每个函数中声明 global $link。这很烦人,有什么办法可以避免多次使用它?或者在不声明全局的情况下解决问题?
提前致谢
【问题讨论】:
-
是的,你必须在每个函数中使用 GLOBAL 关键字,这就是它的工作原理,否则将 $link 变量作为参数解析到每个函数,或者考虑 OOP 范式
标签: php