Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I made a WordPress plugin like this:

Class MY_CLASS {
//codes
}
Global $myclass;
$myclass = New MY_CLASS ();

After installed and activated the plugin, can I use this class in other plugins without including the myclass.php file? For example, in another plugin:

Global $myclass;
$myclass->a = 'dog';
share|improve this question

2 Answers 2

up vote 11 down vote accepted

Technically, it is possible. But I would use a slightly different approach. If your second plugin is loaded first you get an error. If you want to replace the class in another plugin, it is hard to do this.

So hook into plugins_loaded with a specific priority to create the object and use the object in your second plugin on the same hook with a lower (later) priority:

Plugin 1

add_action( 'plugins_loaded', array ( 'My_Class', 'init' ), 10 );

class My_Class
{
    /**
     * Handler for the action 'init'. Instantiates this class.
     *
     * @since 0.1
     * @return void
     */
    public static function init()
    {
        // Named global variable to make access for other scripts easier.
        $GLOBALS[ __CLASS__ ] = new self;
    }
    public function __construct() { /* Do something awesome. */ }
}

Plugin 2

add_action( 'plugins_loaded', 'depending_operation', 11 );

function depending_operation()
{
    if ( empty ( $GLOBALS[ 'My_Class' ] ) )
    {
        return;
    }
    /* Do something awesome again. */
}

Note the 10 and the 11 in add_action()? This guarantees that your second plugin will never run before the first. It still has to check if the first plugin is active and working.

Now you can even replace the class in another plugin:

Plugin 3

add_action( 'plugins_loaded', 'replace_global_class', 12 );

function replace_global_class()
{
    $GLOBALS[ 'My_Class' ] = new Replacement_Class;
}

class Replacement_Class {}
share|improve this answer
1  
Thanks, toscho! You are a great helper! –  Jenny May 11 '11 at 11:39
1  
+1 on this A! Anyway, I'd (personally) use a priority of 9, because 10 is standard and the argument is optional. –  kaiser May 11 '11 at 17:18

Only the main plugin file will be included automatically. So if your plugin is structured like this:

  • wp-content/plugins/my-plugin/
    • my-plugin.php
    • my-class.php

Only my-plugin.php will be included by WordPress. You can make sure that MyClass is available to others by including my-class.php from your my-plugin.php file.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.