How to include one class/instance without using global variables

global variables are not a good solution

Yes, I heard this sentence a lot of times, but as you experienced, sometimes some variables need to be accessed everywhere.

Some modern PHP frameworks implement advanced patterns like IOC that helps in such type of things, but wordpress lacks in that, and this is the reason a lot of global variables is used in WP.

Generally speaking, in PHP, solutions are:

  1. Sigleton. A lot of coder (specially from other languages than PHP) says singleton sucks because are a sort of masked globals. In my opinion, when you can’t rely in an implementation of IOC, singleton are better than ‘pure’ globals, but for simple tasks is not necessary implement this pattern.
  2. Globals. In PHP the keywords global let global vars smell a little less. If you make a thoughtful use, globals doesn’t suck so much. E.g. using them inside functions is not a very bad solution.

Strictly related your case, a static method will suffice as alternative to globals, if you just hate them.

class MyDetect {

  static $detect = NULL;
  static $deviceType = NULL;

  static function detect() {
    if ( is_null(self::$detect) ) {
      require_once '_/inc/md/Mobile_Detect.php';
      self::$detect = new Mobile_Detect;
      self::$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); 
    }
  }

}

Require the file containing the class in your plugin, then

add_action('wp_loaded', array('MyDetect', 'detect') );

and when you need the $detect variable (the mobile detect instance) use MyDetect::$detect and when you need the $deviceType variable use MyDetect::$devicType

Edit: an example of usage

function add_mobile_scripts() {
   wp_enqueue_script('my_script_for_mobiles', 'the_script_url_here' );
}

function add_phone_scripts() {
   wp_enqueue_script('my_script_for_phones', 'the_script_url_here' );
}

function add_tablet_scripts() {
   wp_enqueue_script('my_script_for_tablets', 'the_script_url_here' );
}

function add_desktop_scripts() {
   wp_enqueue_script('my_script_for_desktops', 'the_script_url_here' );
}

function addDevicesScripts() { 
  if ( MyDetect::$deviceType == 'phone' || MyDetect::$detect == 'tablet' ) {
    add_mobile_scripts();
    if ( MyDetect::$deviceType=='phone' ) {
      add_phone_scripts();
    } else {
      add_tablet_scripts();
    }  
  } else {
     add_desktop_scripts();
  }
}

add_action( 'wp_enqueue_scripts', 'addDevicesScripts' );

Leave a Comment