Using PHP Class Methods as WordPress Action Hook Callbacks

Friday, November 20th 12:46am Matt

Using object oriented code is a must for me. Object oriented code is more than just organization of the code, it’s organization of one’s thinking. I wanted to talk about using static class methods as handlers for WordPress actions. This is important to me because often my plugins are implemented as a class.

add_action('init', 'MyPlugin::Init');

class MyPlugin
{
    public static function Init()
    {
        // Put Some Code Here
    }
}

Pretty easy. What I really like about this is that the class name acts as a namespace, so I can use the simple function name Init instead of naming my function something annoying like myplugin_init.

I use this pattern all the time to initialize an instance of the class so that it can be used elsewhere, such as in a theme:

add_action('init', 'MyPlugin::Init');

class MyPlugin
{
    private $userName = null;

    public static function Init()
    {
        global $myPlugin;

        $myPlugin = new MyPlugin();

        // The following line would probably go into a 
        // constructor method and get the real current
        // user name.

        $myPlugin->userName = 'bob';
    }

    pubic function GetUserName()
    {
        return $this->userName;
    }
}

Then any other non-plugin code, like a theme for instance, can detect the presence of the plugin and use it.

global $myPlugin;

if (isset($myPlugin))
{
    echo 'MyPlugin is installed, ', $myPlugin->GetUserName();
}

Happy Coding!

1

Martin Yarcheeck

Tuesday, February 16th 3:50pm

Hi, thanks for sharing your tip. This exactly the way I wont to use, but when I try your simple example I got warning:

Warning: call_user_func_array() [function.call-user-func-array]: Unable to call MyPlugin::Init() in /var/www/vhosts/coca-design.com/subdomains/cms2/httpdocs/wp-includes/plugin.php on line 339

Are you sure, you use this exactly like you described?

BTW: My hole plugin file looks this:
/*
Plugin Name: MyPlugin
*/

add_action(‘init’, ‘MyPlugin::Init’);

class MyPlugin
{
public static function Init()
{
// Put Some Code Here
}
}

2

Martin Yarcheeck

Tuesday, February 16th 4:05pm

Ok, I allready did :)

add_action(‘init’, array(‘MyPlugin’, ‘Init’));

3

Matt

Tuesday, February 16th 4:33pm

Hmmm… what version of PHP are you running on?

Submit a Comment