1

Using the following as an example (with $db being a previously created database connection object)...

Class Session {
   function write_log () {
     global $db;
     $db->query(...);
   }
}

Is there a way to avoid having to write "global $db" everytime I want to use the $db object inside of another class? In other words, declare the $db object as a superglobal from the very beginning.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Joe Smack
  • 465
  • 1
  • 7
  • 16
  • Related: http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-organize-and-access-your-helper-objects – Pekka Sep 15 '10 at 21:00
  • possible duplicate of [Best way to access global objects (like Database or Log) from classes and scripts?](http://stackoverflow.com/questions/1967548/best-way-to-access-global-objects-like-database-or-log-from-classes-and-scripts) – Wrikken Sep 15 '10 at 21:07

2 Answers2

6

Pass the $db to the class constructor:

class Session {
    function __construct($db) {
        $this->db = $db;
    }

    function write_log () {
        $this->db->query(...);
    } 
}

And call it with:

$session = new Session($db);
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • 2
    That is the right way... using globals will make your code unreadable,unmaintainable and after some months or years unusable... – hacksteak25 Sep 15 '10 at 20:49
5

Superglobals are a specific set of built in variables provided by PHP that are accessible anywhere without having to be declared with global:

$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV

In general, is not possible to create your own superglobals.

You could however add a $db member to your Session class, and refer to $this->db instead:

class Session
{
   public $db;

   function __construct()
   {
     $this->db = ... // set up $db object
     // ...
   }

   function write_log ()
   {
     $this->db->query(...);
   }
}
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153