i am trying to get to grips with OOP a little better.
i am using this __construct method wthin all my class files This is functioning fine, and as expected
private $conn; // database connection
// make database connection if not exist!
function __construct() {
// autoload class files
require_once('class/autoloader.php');
spl_autoload_register('myAutoloader');
// open db connection so it is available to all files
$db = new dbconn();
$this->conn = $db->get_connection();
}
However, i have multiple class files that all reference eachother, so as the database connection is being loaded into all class files does this mean i am opening too many connections. AND do i need to close each instance of the connection? (if so this is tricky as i dont always know what class files may have been initiated).
I would be grateful for any advice!
The code above does not give enough context to answer if anything is actually wrong.
Some things to keep in mind.
the __construct function will get called anytime you create a new instance of this class. If you only create one instance of this class and share the instance with any of the other classes you are using, you will be fine.
// Use DI to pass in the database connection.
function __construct($dbConn) {
$this->conn = $dbConn;
}
@Ford another thing you could do is create a function that will connect to the database when it is called. This way you do not have your database connection active even when you are not using it. It would allow your scripts to run a little bit faster because you will be calling a resource only when you need it.
You can also have a close connection function that you will call whenever you are done executing your queries and no longer in need of your DB connection.