Accessing mysqli object in classes
Posted: Fri Sep 04, 2009 5:51 pm
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.
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:
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.
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.
Code: Select all
// {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());
}I have a PHP book that uses a separate mysql_connect.php file, and does it this way:
Code: Select all
$GLOBALS['DB'] = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);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.