Dave Siegel
Dave Siegel

Reputation: 203

Setting one global instead of in every function?

As it is right now, i have my class system to be embedded in my core class. So i call my classes as such:

$cms->userClass->function();

But this means that for every function i have in my userClass, i constantly need to add:

global $cms;

To be able to access the database class as such:

$cms->db->function();

Is there any way to set a global for the whole class, instead of having to define it at the start of every function?

Upvotes: 2

Views: 130

Answers (2)

Ben
Ben

Reputation: 62356

Instead of using functions everywhere, if you build your own classes and put those functions within the classes you could set a single property within the class and access everything by $this->var....

$class = new MyClass($cms);
echo $class->cms; //doesn't work cause it's private

class MyClass () {
    private $cms;  //private so it's only accessible within this class

    function __construct ($cms) {
        $this->cms = $cms;
    }

    //all your functions here can use $this->cms
    function myFunction () {
        echo $this->cms->func(); //this will work
    }
}

Upvotes: 5

Aurel Bílý
Aurel Bílý

Reputation: 7963

I don't think there is global for a class.

However, a couple of alternatives:

  • have a reference to the global $cms variable in a class, so:

    private $cmsref;
    function __construct(){
        global $cms;
        $this->cmsref = &$cms; // $this->cmsref will be a reference to $cms now
    }
    
  • use the superglobal $_GLOBALS:

    function foo(){
        // to access $cms:
        $_GLOBALS["cms"];
    }
    

Upvotes: 1

Related Questions