3

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

1
  • what you aim for will produce a lot of duplicate code that is hard to test. just saying, it's technically possible to do what you ask for, the question is more do you really want that? Commented Feb 1, 2012 at 16:56

4 Answers 4

1

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 require outside the function?

Sign up to request clarification or add additional context in comments.

1 Comment

yes i know globals are bad thus i have avoided using it. reason why i want it outside, is because i want to require it once only, and not for each and every one of my functions.
1

Really the only alternative to globals is to use object orientated tricks and techniques. For example if you implement your functionality as a set of classes then you can always access any static public class variables, as they will be global. Another way is to use a standard PHP pattern for a single object class. This is especially relevant in your case as you seem to be wrapping the standard PDO class. In my case, I use mysqli, but the same technique applies. Any module can access the database object using AppDB::get(). Here is the preamble to my module to give you the idea (I've trimmed the doxygen documentation to keep it short):

class AppDB extends mysqli {            

    /**            
     * This class uses a standard single class object pattern.            
     */            
    private static $_instance;            
    private static $_class = __CLASS__;            
    private function __clone() {}            
    /**            
     * Initialise the blog context. This is a static method since only one AppDB instance is allowed. The            
     * $connectParams must be provided on first invocation.            
     */            
    public static function get() {            

        if ( !isset( self::$_instance) ) self::$_instance = new self::$_class ();            
        return self::$_instance;            
    }            

    /**            
     * AppDB constructor. Connect to the database and initialise the list of tables with the given prefix.            
     */            
    private function __construct() {            

        parent::init();            
        list( $host, $db, $user, $passwd, $this->tablePrefix ) = explode ( ':', SQL_CONTEXT );            

        if( !parent::real_connect($host, $user, $passwd, $db)) {            
            throw new Exception ('Connect Error (' .             
                mysqli_connect_errno() . ') ' . mysqli_connect_error() );            
        }            
        ...            
    }
    ...
}

Comments

0

You can use the global operator:

require('db.inc.php')
function add() {
        global $DBH;
        $n = $DBH -> prepare("");
        $n -> execute((array)$s);
}

Comments

0

You just want to use the global keyword to bring it in the function's scope:

function add() {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}

See this link for more reading on variable scope.

You could also use $GLOBALS, but I'm not a fan of this approach.

Alternatively, you could pass the handle by reference when you call add():

add($DBH);

function add(&$DBH) {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.