Storing state between hook functions

I have two functions which I’m hooking into a plugin. Both functions are called (at different times) during a single page creation by the server.

I want to set a flag in function_a which can be read by function_b.

Read More

Question: Is there any problem with just declaring my flag in the global scope? Is there a preferred WP-style for doing this?

ps. I realize that I will need to be defensive when function_b reads the flag–by making sure that the value was explicitly set, etc.

Related posts

1 comment

  1. Uing OOP for your plugin it’s very easy.

    class MyPlugin {
    
        static $flag;
    
        static function function_a() {
          self::$flag = 'a value';
        }
    
        static function function_b() {
          if ( ! is_null(self::$flag) ) echo self::$flag; // echo 'A Value';
        }
    
    }
    
    add_action('plugins_loaded', array('MyPlugin', 'function_a') );
    add_action('init', array('MyPlugin', 'function_b') );
    

    Not using OOP you can use global variables.

    function function_a() {
      global $myflag;
      $myflag = 'a value';
    }
    
    function function_b() {
      global $myflag;
      if ( ! is_null($myflag) ) echo $myflag; // echo 'A Value';
    }
    
    add_action('plugins_loaded', 'function_a' );
    add_action('init', 'function_b' );
    

    This works and seems easier, but first solution is better for sure.

Comments are closed.