user1318194
user1318194

Reputation:

Best way to use MySQLi inside a class

Currently I'm doing this:

function __construct( $mysqli_connection )
{
    if( ! empty($mysqli_connection) && is_object($mysqli_connection) && ! $mysqli_connection->connect_error )
    {
        //Make the $mysqli universal to the class equal the given connection
        $this->mysqli = $mysqli_connection;
    }
    else
    {
        die("An invalid MySQLi connection was given.\n");
    }

}//function __construct

And the initiating the class with:

new className( $mysqli );

It works fine, however it seems to me that:

Are my above points true, and if so, is there a better way to use a MySQLi resource from inside a class? The above method is the only way I've found from searching.

Upvotes: 1

Views: 2006

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173542

First of all, your code can be reduced to:

private $mysqli;

function __construct(mysqli $conn)
{
    $this->mysqli = $conn;
}

Your class shouldn't have to worry about whether the connection was established, it should be able to assume that it is. Also, type hints help to indicate what class is expected when the constructor is called.

Second, the mysqli object is not duplicated when you're using it inside another object; instead, its reference count is increased. Once the count drops to zero the object gets removed. If an object was always copied, doing dependency injection would become very expensive.

Upvotes: 3

Related Questions