Declare Global Variable In OOP PHP

I'm working on my Plugin i wanted to declare one of the global wordpress variables which is $current_screen To Check whether The user is on the target page or some other page, my Approach was like this , but it didn't work out .

class my_Class {

    public $current_screen;

    public function __construct() {
        global $current_screen;
        add_action( 'current_screen', array( $this, 'Current_Screen') );
    }

    public function Current_Screen() {
         if ( $current_screen-parent_base == 'slug-page' ) {
             // Do Something ...
         }
    }
}

Unfortunately Nothing Happens but Fatal Error . So Please Guys I Wanna Help . Thanks In Advance .

Topic screen-options globals errors Wordpress

Category Web


It's not enough to call global in __construct(). global only makes the variable available in the current scope, which is just the __construct() method.

To make it available in other methods you need to call it in each method individually:

class MyClass {
    public function __construct() {
        add_action( 'init', array( $this, 'method') );
    }

    public function method() {
        global $global_variable;

         if ( $global_variable ) {
             // Do Something ...
         }
    }
}

The other option is to assign the global variable as a class property, then refer to it in each method with $this->:

class MyClass {
    public $property;

    public function __construct() {
        global $global_variable;

        $this->property = $global_variable;

        add_action( 'init', array( $this, 'method') );
    }

    public function method() {
         if ( $this->property ) {
             // Do Something ...
         }
    }
}

However, as noted by Nathan in his answer, you need to be wary of when your class is instantiated, as it's possible that the global variable will nit be available at that point.

In those cases you would need to use my first example so that the variable is only referenced in a function that is hooked into the lifecycle at a point where the variable has been created.


The $current_screen is passed as a variable to callables hooked from the current_screen hook.

Before this hook, the $current_screen isn't set up, so globalizing the variable won't do anything anyway.

Also, WordPress offers the convenience function get_current_screen() that returns the global $current_screen variable if it exists.

class wpse {
  protected $current_screen;
  public function load() {
    add_action( 'current_screen', [ $this, 'current_screen' ] );
  }
  public function current_screen( $current_screen ) {
    $this->current_screen = $current_screen;
  }
}
add_action( 'plugins_loaded', [ new wpse(), 'load' ] );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.