函数中来自不同文件的变量而不使用全局变量

Variable from different file in function without using global

嗯,

我定义了(在config.php):

$mysql = mysqli_connect (..);

用于连接到 mySQL 数据库。 现在我想在我的函数中使用变量 (functions.php):

function x () { $fetch = ($mysql, "SELECT ...")); }

不使用全局:

function x () { global $mysql ... }

任何干净的想法(程序)?

您可以例如将连接资源传递给您的函数

function x ($mysqli) { $mysqli->... }

您可以通过使用超全局 $GLOBALS:

访问 global-scope 中的变量而无需 global-keyword
function x() { $GLOBALS['mysql']->... }

文档:http://php.net/manual/en/reserved.variables.globals.php

我建议创建一个单独的函数,returns 您可以使用 Database-Handle/Object 代替变量。例如:

function db() { return $GLOBALS['mysql']; }
function x() { db()->... }