I have various php files which access a DB. I have created a file which I have called ostendoconnection.php with the necessary variables.
I wish to access this file anytime I want to make a connection to the php.
The php file would look something like
<?php
include ostendoconnection.php
$db = ibase_connect($ODB_SERVER, $ODB_USER, $ODB_PASSWORD);
...
?>
It works fine in some instances. But when I have a php file of functions and declaring include ostendoconnections.php
doesn’t connect to the db and I have to make the connection in each function, which is not ideal.
<?php
include ostendoconnection.php
function name(parameter) {
$ODB_SERVER = 'blalblalbla' ;
$ODB_USER = 'bla' ;
$ODB_PASSWORD = 'bla2' ;
$db = ibase_connect($ODB_SERVER, $ODB_USER, $ODB_PASSWORD);
...
}
function name2(parameter) {
...
}
?>
Currently I am accessing a daily backup of the db and I want to just change the db name in one place, hence the creation of ostendoconnection.php!
What am I doing wrong?
2
Answers
There are couple of ways to handle this, I think one of them is use of the the
global
keyword inside your functions to access global variables. Hope this helps.You can use a pattern called Dependency Injection. Rather than having each method creating its own resources, you provide a ready to use resource. Your code is procedural rather than object-oriented, but the concept still applies:
You can even create
$db
insideostendoconnection.php
, so you don’t have to repeat that part in every file.