Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a variable globally visible without having to declare it global in every single PHP class's constructor?

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?

like image 560
Dave Hunt Avatar asked Aug 05 '09 16:08

Dave Hunt


2 Answers

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.

  class myClass
   {
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new myClass;
        }
        else
        {
            return self::$class;
        }
    }
    // Then create regular class functions.
   }

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

like image 122
Tyler Carter Avatar answered Sep 18 '22 13:09

Tyler Carter


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):

define('APPLICATION_ID', 'myApplication');

${APPLICATION_ID} = new App;

function app() {
    return $GLOBALS[APPLICATION_ID];
}

So then I can use something like the following anywhere in any code to reference objects within the global object:

app()->db->read($statement);
app()->cache->get($cacheKey);
app()->debug->set($message);
app()->user->getInfo();

It's not perfect but I find it to make things easier in many circumstances.

like image 43
conceptDawg Avatar answered Sep 18 '22 13:09

conceptDawg