PHP All Function Variables Global
I have a function called init on my website in an external file called functions.php. Index.php loads that page and calls function init:
function init(){
error_reporting(开发者_如何学JAVA0);
$time_start = microtime(true);
$con = mysql_connect("localhost","user123","password123");
mysql_select_db("db123");
}
How can I get all of these variables global(if possible) without having to use
global $time_start;
global $con;
You don't want it global.
On alternative is to encapsulate it in a object or even use a DI in order to configure it.
If you want to specifically use globals, take a look at $GLOBALS array. Even though there are couple of other ways, Pass by reference, Data Registry Object recommended, etc.
More on variable scopes.
Maybe you can return these variables from your init() function :
function init(){
error_reporting(0);
$time_start = microtime(true);
$con = mysql_connect("localhost","user123","password123");
mysql_select_db("db123");
return array('time_start' => $time_start, 'con' => $con);
}
You can declare them in the global scope, then pass them to the function by reference. After modifying the function to do so.
精彩评论