2

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Dave Siegel
  • 203
  • 1
  • 10
  • 1
    Related: http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-store-access-and-organize-your-helper-objects – Unicron Mar 19 '11 at 13:49

2 Answers2

5

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
    }
}
Ben
  • 60,438
  • 111
  • 314
  • 488
  • And if used with dependency injection, this approach can be VERY flexible. – Major Productions Mar 19 '11 at 13:58
  • 2
    I'd make one tweak here... unless the $cms *must* be a public, I'd go ahead and flip it to protected and just have a getter return it. Then the context of $cms is much less likely to change by accident during execution. – CaseySoftware Mar 19 '11 at 14:07
  • @Casey - good thinking. I changed it. If you passed $cms into the class, it's likely that you already have an instance of it outside the class and don't need it to be public – Ben Mar 19 '11 at 17:46
  • Just to be a little more annoying.. I personally stay away from private (and final). When you use one of those, anything that extends your class can't get at the value. There are lots of times where accessing it would be legitimate. On the other hand, using protected still tells people "hey, don't mess with this" but adds "unless you *really* need to and have a clue on what you're doing". My 0.02 – CaseySoftware Mar 20 '11 at 18:03
1

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"];
    }
    
Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
  • [Globals are evil](http://stackoverflow.com/questions/5166087/php-global-in-functions/5166527#5166527) – Gordon Mar 19 '11 at 14:16