简体   繁体   English

在全局变量PHP中定义Globals

[英]Defining Globals inside global variables PHP

I am forever going up and down my code adding and removing globals to functions. 我一直在上下我的代码添加和删除全局变量到函数。

Is it possible to pass global variables inside global variables to functions to save defining them in each time in function? 是否有可能将全局变量传递到全局变量中的函数,以便在每次函数中保存定义它们? If not is there a better way to do this? 如果没有,有更好的方法吗?

My aim is to have an index of global variables at the top of each page and not worry about having to defining them inside functions. 我的目标是在每个页面的顶部都有一个全局变量索引,而不必担心必须在函数内部定义它们。

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

Im not sure if I understood well. 我不确定我是否理解得很好。 But why don't you make $site and array instead of a string ? 但是你为什么不制作$site和array而不是字符串呢?

Like this : 像这样 :

$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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM