• I need to get information from another plugin but I get an undefined variable error when trying to call the function from the object created in the first plugin. As far as I know plugins are loaded in alphabetical order from the active_plugins option. To help solve this I used a bit of code that changes the order so that the required plugin is at the front of active_plugins but the error persists.

    My dev environment is PHPStorm which even allows me to click through from the second plugin to the first from the function call. This says to me that the first plugin object should be seen as long as the first plugin is loaded.

    Plugin A

    class PluginA {
        public function check() {
            return 'checked';
        }
    }
    
    $example = new PluginA();

    PluginB

    class PluginB {
        public function plugina_check() {
            // Check to see if plugin is active is true
            if (in_array('plugina/class-plugina.php', get_option('active_plugins')) {
                // The next call throws Undefined variable $example
                $result = $example->check();
            }
        }
    }

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Bushstar

    (@bushstar)

    Actually, I have solved this but I am not sure it is best practice. In PluginB I have updated it to the following.

    class PluginB {
        public function plugina_check() {
            // Check to see if plugin is active is true
            if (in_array('plugina/class-plugina.php', get_option('active_plugins')) {
                // Create mew object
                $new_example = new PluginA();
    
                // The next call throws Undefined variable $example
                $result = $new_example->check();
            }
        }
    }

    I assumed that the first objected created should be available to other plugins and that creating a second object would be unnecessary. I have now created two objects of the PluginA class.

    Asyou’ve seen, variable scope can be an issue for development. Any variables that exist inside functions exist only in those functions, and you can’t access outsdie variable without them being passed in or made global.

    If $example is set in the global scope you can also use this to access the original value:

    class PluginB {
        public function plugina_check() {
            // Check to see if plugin is active is true
            if (in_array('plugina/class-plugina.php', get_option('active_plugins')) {
                // Global value
                global $example;
    
                // The next call throws Undefined variable $example
                $result = $example->check();
            }
        }
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Calling plugin function from another plugin’ is closed to new replies.