Must activation/deactivation functions in a class be static?

The description for register_uninstall_hook‘s $callback parameter states:

Must be a static method or function.1

There is no such comment for register_activation_hook or register_deactivation_hook. However, in the Codex entry for register_activation_hook there is an example that reads:

Or, because the activation hook requires a static function, if you’re inside of a __construct():2

In a GitHub issue, “why is activate a static method?”, a user states:

You can’t define them as standard functions because they require an instance of the plugin to fire, but you can’t instantiate the plugin prior to firing the activation function because the constructor will fire (even if it’s empty), so functions need to be marked as static so that any preliminary work required to prepare the plugin for de/activation can be set.3

When using classes to (de)activate a plugin, are the functions required to be static? If so, is the explanation as to why correct?

2 s
2

Depends the way you want to implement it. The static is used because you don’t have to instantiate the class to use the functions of the class. It’s up to you. I generally would do:

<?php

/*it's good practice that every class has its own file. So put it in for example 'classes/class-hooks.php' and require it properly in your plugin file. */

class Hooks{
    static function activation(){
       //the code you want to execute when the plugin activates
    }

    static function deactivation(){
       //the code you want to execute when the plugin deactivates
    }

    static function uninstall(){
      //the code you want to execute when the plugin uninstalled
    }

}

...

// you should use this in your plugin file

register_activation_hook(__FILE__, 'Hooks::activation' );
register_deactivation_hook(__FILE__, 'Hooks::deactivation');
register_uninstall_hook(__FILE__, 'Hooks::uninstall');


This is the simple way I know to do it and the plugins I read the code generally does that way. Hope that helps!

Leave a Comment