Forum Moderators: coopster

Message Too Old, No Replies

Accessing mysqli object in classes

Globals? Include_once? Pass to method?

         

curlybill09

10:57 pm on Sep 4, 2009 (gmt 0)

10+ Year Member



Hi guys,

I'm relatively new to OOP php and have been creating a bunch of classes (user class, validation class, etc). I have a separate php file (mysqli_connect.php) that resides in web root that all my scripts include. This mysqli_connect.php uses the mysqli OO connection, as opposed to the procedural.

// {mysqli_connect.php}
// Instantiate MySQL connection object:
$dbc = @new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno())
{
throw new RuntimeException('Cannot access database: ' . mysqli_connect_error());
}

My classes are placed in their own separate php files. And many methods in these classes require use of the mysqli database connection above. I don't want to pass the actual $dbc mysqli object to the class simply to allow the class access to the connection. And I don't want to have to include mysqli_connect.php at the top of every single class file.

I have a PHP book that uses a separate mysql_connect.php file, and does it this way:

$GLOBALS['DB'] = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

But I've heard somewhere that using $GLOBALS is just plain BAD. Is it a legitimate technique? Are there risks to placing the mysqli object in $GLOBALS['DB']? To be honest, I've never even used the $GLOBALS superglobal before.

What do you guys do? What do you suggest? I'm looking for a "proper" and professional way of sharing that mysqli connection object with all my classes. Thanks so much for your help and guidance.

coopster

2:30 pm on Sep 5, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You may consider the singleton factory as described in this thread asking how to provide Access to a class from inside another [webmasterworld.com]