Is it a best practice to initialize an object and store in global variable. for example something like this?
$GLOBALS[‘db’] = new Sql();
Can anyone tell why it is good or why it is bad?
Is it a best practice to initialize an object and store in global variable. for example something like this?
$GLOBALS[‘db’] = new Sql();
Can anyone tell why it is good or why it is bad?
I suspect you don’t understand what “global variable” is
$db = new Sql();
is enough and will be already global variable, if you don’t place this code inside of some function.
It’s a common practice. Whether it’s good or bad, is a different matter.
Well, global variables have a number of problems associated with them. Most generally speaking, they add implicit dependencies to your application, and this in turn causes the application to be harder to maintain. Depending on your applications size, that may be a small or a big issue, but keep in mind that large applications have a tendency to start out as small applications.
Note also that global variables comes in many shapes and forms. For example, a singleton is arguably a kind of global variable. So is a static class member.
Use Singleton Registry Pattern instead.