My advice is to avoid being global in the amount of code - this is dangerous, difficult to track and will bite you.
What I will do is to have a function called getDB (), which can either be at the class level, either by embedding the constructor, or from a static within the general class.
So the code becomes
class SomeClass { protected $dbc; public function __construct($db) { $this->dbc = $db; } public function getDB() { return $this->dbc; } function read_something() { $db = getDB(); $db->query(); } }
or using a common common class.
function read_something() { $db = System::getDB(); $db->query(); }
No matter how elegant the design of the system you are doing, there are always several elements that are necessarily global in volume (for example, DB, Session, Config), and I prefer to store them as static methods in my System class.
Each class requires a connection through the constructor, this is the best way to do this, I would best mention the most reliable and isolated ones.
However, keep in mind that using a common general class for this can affect the ability to completely isolate objects that use it, as well as the ability to perform unit tests for these objects.
source share