【问题标题】:Not able to pass variable from different php file无法从不同的php文件传递变量
【发布时间】: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 文件是这样连接的 -

  1. functions.php 在 index.php 中是必需的(使用 require)

  2. 在functions.php中需要db_functions.php(使用require)

  3. 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


【解决方案1】:

tim 说的是对的,另一种不实现 OOP 的方法是使用超全局 $GLOBAL

例如。 $GLOBALS['link']

参考:https://www.php.net/manual/en/reserved.variables.globals.php

【讨论】:

  • 虽然这不是我正在寻找的答案,但由于 PHP 中没有其他选项,我必须使用 OOP 或 $GLOBALS['link']
猜你喜欢
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 2014-02-03
  • 1970-01-01
  • 2015-11-16
相关资源
最近更新 更多