在全局变量PHP中定义Globals

时间:2013-05-25 14:14:24

标签: php function global-variables

我一直在上下我的代码添加和删除全局变量到函数。

是否可以将全局变量中的全局变量传递给函数,以便在每次函数中保存定义它们?如果不是,有更好的方法吗?

我的目标是在每个页面的顶部放置一个全局变量索引,而不必担心必须在函数内定义它们。

global $site;
$site = "global $link, $create, $populate, $delete, $withdraw";

$host = "";
$username = "";
$password = "";
$database = "";

$link = mysqli_connect("$host", "$username", "$password", "$database");

function display() { global $site; // code }
function populate() { global $site; // code }
function create() { global $site; // code }
function withdraw() { global $site; // code }

    //output

1 个答案:

答案 0 :(得分:2)

我不确定我是否理解得很好。但是为什么不用$site和数组而不是字符串?

像这样:

$host = "";
$username = "";
$password = "";
$database = "";

$link = mysqli_connect("$host", "$username", "$password", "$database");

$site = array(
  'link'     => $link,
  'create'   => $create,
  'populate' => $populate,
  'delete'   => $delete,
  'withdraw' => $withdraw,
);

function display() {
  global $site;
  // Here you can access & modify your $site array
}