PHP : Make other functions access the $conn variable inside my database connection function

Your Desired Solution: This should work, and you'll only make one connection.

function db () {
    static $conn;
    if ($conn===NULL){ 
        $conn = mysqli_connect ("localhost", "root", "", "database");
    }
    return $conn;
}

function someFunction () {
    $conn = db();
    $result = mysqli_query ($conn, "SELECT * FROM examples);
}

If you used the function someFunction($conn), that would make your code much messier, since you wouldn't actually have universal access to $conn from anywhere.

You should go with Solution B IMO. That way, you can have simple access to it Database::$conn which will be consistent throughout your script. You could should have an initialize function (you could use a different name if you want) that will initialize Database::$conn, and you can then use that to initialize other things on the Database class later, if desired.

Solution A is terrible. I did that for a long time (globalizing things), and it was a horrible idea. I should have never done that. But I did. And I learned. It just made code get progressively sloppier and sloppier.

Solution B: Database::$conn should be public if you want to be able to access it by Database::$conn from anywhere. If it's private, then you would always need to call Database::getObject();

Solution C: You're right. That would be very impractical.

Solution B rewrite:

class Database
{
    /** TRUE if static variables have been initialized. FALSE otherwise
    */
    private static $init = FALSE;
    /** The mysqli connection object
    */
    public static $conn;
    /** initializes the static class variables. Only runs initialization once.
    * does not return anything.
    */
    public static function initialize()
    {
        if (self::$init===TRUE)return;
        self::$init = TRUE;
        self::$conn = new mysqli("localhost", "root", "", "database");
    }
}

Then... call Database::initialize() at least once before it gets used.

<?php
Database::initialize();
$result = mysqli_query (Database::$conn, "SELECT * FROM examples);
?>

EDIT

  • You can also call Database::initialize() immediately after the declaration of the class, in that PHP file. Then initializing is handled.
  • I'm now far more fond of something like Database::getDb() than accessing the $conn property directly. Then initialize can be called from the getDb() function. Basically like the Desired Solution but inside a class. The class really isn't necessary, but it can be nice if you like classes, like I do.

Tags:

Php