Edward
Edward

Reputation: 9778

PHP: Globals, SuperGlobals - How to make a variable's value accessible to all functions?

I have a PHP program I'm writing which is about 200 lines of code. It has many functions I wrote, perhaps a dozen. I want to have a debug option in the program, but want that value to be accessible within all the functions as well. How and where should this be defined?

Global $debug_status;

function blah ($message) {
if ($debug_status == "1" ) {
  do something...}
...
}

Is this the right approach? Thanks!

Upvotes: 1

Views: 587

Answers (3)

Robert
Robert

Reputation: 20286

The variable should be defined in Registry class which is sort of pattern.

Working demo

Example of Registry

class Registry {
   private static $registry = array();

   private function __construct() {} //the object can be created only within a class.
   public static function set($key, $value) { // method to set variables/objects to registry
      self::$registry[$key] = $value;
   }

   public static function get($key) { //method to get variable if it exists from registry
      return isset(self::$registry[$key]) ? self::$registry[$key] : null;
   }
}

Usage

To register object you need include this classn

$registry::set('debug_status', $debug_status); //this line sets object in **registry**

To get the object you can use get method

$debug_status = $registry::get('debug_status'); //this line gets the object from **registry**

This is solution that every object/variable can be stored in. For such purpose as you wrote it's good to use simple constant and define().

My solution is good for every kind of object that should be accessed from anywhere in application.

Edit

Removed singleton and make get, set methods as static as @deceze suggested.

Upvotes: 1

deceze
deceze

Reputation: 522210

Use a constant.

define('DEBUG', true);

...

if (DEBUG) ...

There are of course better ways to debug. For example, use OOP, inject a logger instance into each of your objects, call

$this->logger->debug(...);

to log messages, switch the output filter of the logger to show or hide debug messages.

Upvotes: 3

Orangepill
Orangepill

Reputation: 24645

You were almost there .... the global keyword imports a reference to a global into the current scope.

$debug_status = "ERROR";

function blah ($message) {
    global $debug_status;
    if ($debug_status == "1" ) {
      do something...}
      ...
    }

Upvotes: 1

Related Questions