Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing global variables in a separate PHP script?

I'm trying to import some variables from a PHP script. It seems simple but I cannot get it to work.

The script contains some global variables like that:

$server_hostname = "localhost";
$server_database = "kimai";
$server_username = "root";
$server_password = "";
$server_conn     = "mysql";
$server_type     = "";
$server_prefix   = "kimai_";
$language        = "en";
$password_salt   = "7c0wFhYHHnK5hJsNI9Coo";

Then in my script, I would like to access these variables, so I've done:

require_once 'includes/autoconf.php';   
var_dump($server_hostname);

But this just outputs NULL. I've also tried:

require_once 'includes/autoconf.php';

global $server_hostname;    
var_dump($server_hostname);

but still not working.

I've added some echo statements in the "autoconf.php" file so I know that it's being loaded.

Any idea how I could access these variables?

like image 203
laurent Avatar asked May 18 '12 06:05

laurent


People also ask

How can access global variable from another file in PHP?

In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file. In other words: write global $var before you use it in another function.

What is used to access global variables from anywhere in the PHP script *?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index].

Can global variables be accessed from other files?

Global variables and function names have external linkage. These are accessed from other files by declaring them with the keyword extern.


1 Answers

You have to define the variable as global first:

global $server_hostname;
$server_hostname = "localhost";
like image 153
djot Avatar answered Oct 23 '22 04:10

djot