PHP Classes are powerful tool for improving code organization and minimizing naming collisions. At some point or another, the question of how to create an action hook for a class method inevitably arises.
The $function_to_add
argument is often shown as a string containing the function's name, however the data-type of the argument is actually a "callable", which for our purposes can be summed up as "a reference to a function or method".
There are a number of callable formats that can be used to reference methods on classes and objects. In all cases however, the referenced method must be publicly visible. A method is public when it is either prefixed with the public
keyword, or no visibility keyword at all (in which case the method defaults to public).
Object methods are executed on a particular instance of a class.
class My_Class {
// Constructor
function My_Class() {
// (Instantiation logic)
}
// Initialization function
public function initialize() {
// (Initialization logic)
}
}
After instantiating the above class as follows,
$my_class_instance = new My_Class();
the initialize()
method would normally be invoked on the object by calling $my_class_instance->initialize();
. Hooking the method to the 'init'
WordPress action is done by passing an array containing a reference to the instance and a string containing the object method's name:
add_action( 'init', [ $my_class_instance, 'initialize' ] );
If add_action()
is called within an object method, the $this
pseudo-variable can also be used:
class My_Class {
// Constructor
function My_Class() {
// (Instantiation logic)
add_action( 'init', [ $this, 'initialize' ] );
}
// Initialization function
public function initialize() {
// (Initialization logic)
}
}
Class methods are executed statically on a class rather than any particular instance. Given the following class,
class My_Class {
// Initialization function
public static function initialize() {
// (Initialization logic)
}
}
the initialize()
method would normally be invoked by using the ::
scope-resolution operator, i.e. My_Class::initialize();
. Hooking a static class method to a WordPress can be done in a couple different ways:
Using an array composed of a string containing the class name, and a string containing the method name:
add_action( 'init', [ 'My_Class', 'initialize' ] );
Passing a string containing a full reference to the method, including the ::
operator:
add_action( 'init', 'My_Class::initialize' );
If add_action()
is called within a static class method, the self
keyword or the __CLASS__
magic-constant can be used in place of the class name. Note that this is generally inadvisable as the values of these items become somewhat counter-intuitive in the case of class inheritance.
class My_Class {
// Setup function
public static function setup_actions() {
add_action( 'init', 'self::initialize' );
}
// Initialization function
public static function initialize() {
// (Initialization logic)
}
}