Can I make a variable globally visible without declaring it global in every constructor of the PHP class?

I have a database class that an instance is declared in the main index.php as

 $db = new Database(); 

Is there a way that $db should be recognized globally in all other classes without declaration

 global $db; 

in the constructor of each class?

+6
variables oop php class global
source share
5 answers

Not. You must declare a global $ db in the constructor of each class.

or you can use the global array: $ _GLOBALS ['vars'];

The only way around this is to use a static class to wrap it, called the Singleton Method (see here for an explanation). But this is a 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 ensure that there is only one instance of any class. But, since people use it as a way to combine globalling, it becomes known as lazy / poor programming.

Knowledge of Stackoverflow
How to avoid using global PHP objects
Exchange variables between functions in PHP without using globals
Creating a global variable available for each function within the class
Global or Singleton to connect to the database

+16
source share

I do it a little differently. Usually I have a global application object (application). Inside this object, I do some basic initialization, for example, creating db objects, caching objects, etc.

I also have a global function that returns an App object .... this way (the definition of the application object is not shown):

 define('APPLICATION_ID', 'myApplication'); ${APPLICATION_ID} = new App; function app() { return $GLOBALS[APPLICATION_ID]; } 

So, I can use something like the following in any code to refer to objects inside a global object:

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

This is not ideal, but I believe that this facilitates the situation in many circumstances.

+2
source share

you can use

 $GLOBALS['db']->doStuff(); 

or alternatively using some single-threaded access method

 Database::getInstance()->doStuff(); 
+1
source share

Why not create a class containing the global $db; constructor global $db; in it, and then expand all the other classes from this?

+1
source share

You can use the Registry class to store and retrieve your Database instance.

 class Registry { protected static $_data = array(); public static function set($key, $value) { self::$_data[$key] = $value; } public static function get($key, $default = null) { if (array_key_exists($key, self::$_data)) { return self::$_data[$key]; } return $default; } } Registry::set('db', new Database()); $db = Registry::get('db'); 
0
source share

All Articles