Best practice for global variables in an object -

2019-08-07 19:52发布

问题:

I have a question on best practices for PHP OOP, relating the using global variables in methods. I know what I am doing is incorrect, but I am not certain how else it should be done.

We are using this database class: https://github.com/joshcam/PHP-MySQLi-Database-Class/blob/master/MysqliDb.php

We create the object in a config.php file that is required on every page with the following line of code. $db = new MysqliDb(host,user,pwd,dbname);

However, every method in all of our classes must use global $db if we wish to access the database. Is this bad practice? If so, how should this be done? Should all of our classes be extending the database class (MysqlDb)?

回答1:

mysqli-db has a MysqliDb::getInstance() static call to get an initialized object. So you initialize it in config.php with new() and after that use MysqliDb::getInstance() to get an object.