I made a WordPress plugin like this:

Class MY_CLASS {
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';

3 Answers 3


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' ] ) )
    /* 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 {}
  • 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, 2011 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.


toscho's answer worked great! Just to add, if you are making a plugin that is extensible with add-ons, the add-ons can still be OOP.

Plug-in 2

class My_Class_Addon(){
public function __construct() { /* Do something awesome as an addon to My_Class */ }

add_action( 'plugins_loaded', 'My_Class_Addon_loader', 11 );
function My_Class_Addon_loader(){
    if(empty($GLOBALS[ 'My_Class' ])){
    $this_my_class = new My_Class_Addon();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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