Is there a way to include a file outside of a function and have it work?
ie. I have a file db.inc.php, this contains my db connection string:
switch (DB_TYPE) {
case MYSQL :
try {
$DBH = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "", DB_USER, DB_PASS);
$DBH -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error in Connection" . $e -> getMessage();
}
}
Now I have require this file my in my functions file, functions.php:
require('db.inc.php')
function add() {
$n = $DBH -> prepare("");
$n -> execute((array)$s);
}
so the file is added in properly, but my function cannot access the $DBH handle. Only when I include the file in my function:
function add(){
require('db.inc.php')
....etc....
}
will my function work.
As I am going to have at least 4-5 functions in many files, any possibility of just requiring it outside the function and get the function to work?
Thank and regards
After including the file outside the function, you could declare the variable as global, but that’s really a bad way to do things. Instead, you should have the caller of the function pass handle as an argument. Failing that, you could create a factory for the database and call it within each function.
Why do you have to call the
requireoutside the function?