I have a database class, which an instance is declared in the main index.php
as
$db = new Database();
Is there a way for the $db
variable to be globally recognized in all other classes without having to declare
global $db;
in the constructor of each class?
No. You have to declare Global $db in the constructor of every class.
or you can use the Global array: $_GLOBALS['vars'];
The only way to get around this is to use a static class to wrap it, called the Singleton Method (See Here for an explanation). But this is very bad practice.
The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalling, it becomes known as lazy/bad programming.
StackOverflow Knowledge
How to Avoid Using PHP Global Objects
Share Variables Between Functions in PHP Without Using Globals
Making a Global Variable Accessible For Every Function inside a Class
Global or Singleton for Database Connection
Why not create a class that contains the
global $db;
in it's constructor, then extend all other classes from this?I do it a little different. I usually have a global application object (App). Within that object I do some basic initialization like creating my db objects, caching objects, etc.
I also have a global function that returns the App object....thus (application object definition not shown):
So then I can use something like the following anywhere in any code to reference objects within the global object:
It's not perfect but I find it to make things easier in many circumstances.
You could use a
Registry
class to store and retrieve yourDatabase
instance.you could use
or alternatively using some kind of singleton access method