nebkat
nebkat

Reputation: 8565

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(0);
   $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;

Upvotes: 4

Views: 1841

Answers (4)

sepehr
sepehr

Reputation: 18455

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.

Upvotes: 1

mathk
mathk

Reputation: 8143

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.

Upvotes: 3

Romain Deveaud
Romain Deveaud

Reputation: 824

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);
}

Upvotes: 1

Babiker
Babiker

Reputation: 18798

You can declare them in the global scope, then pass them to the function by reference. After modifying the function to do so.

Upvotes: 0

Related Questions