Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid using PHP global objects?

Tags:

php

global

I'm currently creating blog system, which I hope to turn into a full CMS in the future.

There are two classes/objects that would be useful to have global access to (the mysqli database connection and a custom class which checks whether a user is logged in).

I am looking for a way to do this without using global objects, and if possible, not passing the objects to each function every time they are called.

like image 842
Nico Burns Avatar asked Jul 18 '09 17:07

Nico Burns


2 Answers

You could make the objects Static, then you have access to them anywhere. Example:

myClass::myFunction();

That will work anywhere in the script. You might want to read up on static classes however, and possibly using a Singleton class to create a regular class inside of a static object that can be used anywhere.

Expanded

I think what you are trying to do is very similar to what I do with my DB class.

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

What happens is after you get the connection, using $object = myClass::get_connection(), you will be able to do anything function regularly.

$object = myClass::get_connection();
$object->runClass();

Expanded

Once you do that static declarations, you just have to call get_connection and assign the return value to a variable. Then the rest of the functions can have the same behavior as a class you called with $class = new myClass (because that is what we did). All you are doing is storing the class variable inside a static class.

class myClass
{
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new myClass;
        }
        return self::$class;
    }
    // Then create regular class functions.
    public function is_logged_in()
    {
        // This will work
        $this->test = "Hi";
        echo $this->test;
    }
}

$object = myClass::get_connection();
$object->is_logged_in();
like image 106
Tyler Carter Avatar answered Nov 02 '22 01:11

Tyler Carter


You could pass the currently global objects into the constructor.

<?php
  class Foo {
    protected $m_db;
    function __construct($a_db) {
      $this->m_db = $a_db;
    }
  }
?>
like image 45
Eugene Yokota Avatar answered Nov 02 '22 00:11

Eugene Yokota