Use Require_once() to include database connection variables correctly
PHP doesn't have function scope like Javascript, so you do not have access to the variables in db_login.php
inside the functions of functions.php
.
There are multiple ways of dealing with this. Due to your probable use of the server name global constants would probably be a good solution, since nothing can change them.
In your case you can do:
<?php require_once('db_login.php'); // You have access to $db_server here. // Create a constant. define("DB_SERVER", $db_server); function myfunction() { // Using a constant. Note that there is no "$". echo DB_SERVER ; // Constants are interpreted inside double quotes too echo "\nMy constant is DB_SERVER"; // ... }?>
In your case having the server name as a constant is probably appropriate. If you are dealing with something that you want to treat as a true variable, you can pass the variable into the function by value or by reference:
myfunction($variable); // by valuefunction myfunction($pass_variable_to_me_by_value){ echo $pass_variable_to_me_by_value; // ...}function myfunction(& $pass_variable_to_me_by_reference){ echo $pass_variable_to_me_by_reference; // ...}
As a note, in your case, using the global
keyword or the $GLOBALS array inside a function is essentially the same as passing by reference., but if you are not passing from the global scope they can be very different (in a Class or from another function for example).
The variables you declare in db_login.php
are globals. In order to access them in your function, you need to use the $GLOBALS
variable, e.g. $GLOBALS['db_server']
, or declare them as global inside your function using the global
keyword, e.g. global $db_server
.
Inside of the function "myfunction" you don't have access to these variable...
See more in: http://php.net/manual/en/language.variables.scope.php