Reputation: 91
For years I have done something like this:
config.php
<?php
$db = array("user" => "username", "pass" => "password");
functions.php
<?php
require_once('config.php');
function connectToDatabase() {
$dbc = new PDO($dsn, $db['user'], $db['pass']);
// Do some stuff ...
}
I've just read the PHP manual and that SHOULDNT work, but for years it has. Are there any server configurations that allow that to work?
I've just coded a new script and getting errors. The $db array is not even initialized.
Upvotes: 0
Views: 100
Reputation: 449385
This should in fact never work, not even in older PHP versions nor with register_globals
.
To import a global variable into a function, you need a global $varname;
statement, or pass the variable to the function (which is generally preferable, as globals are bad). The only exception are superglobals.
Are you 1000% sure it was not like this:
function connectToDatabase() {
require_once('config.php');
$dbc = new PDO($dsn, $db['user'], $db['pass']);
// Do some stuff ...
}
?
Upvotes: 0
Reputation: 522005
Indeed, there are no variables in scope at the beginning of your connectToDatabase
function. You should have gotten warnings about undeclared variables, too. Maybe it worked because of the configuration of your database installation that caused it use default usernames and passwords?
Upvotes: 3