I recently had to do the same thing and ended up using the static::
late static binding along with special ::class
constant. The static::
binding will reference the calling class, while the ::class
constant will return a string that is the name of the calling class (with namespacing!)
Using the example from the questiom, the implementation would like something like this:
class LocatorMap {
public static function init() {
add_action( \'wp_enqueue_scripts\', array( static::class, \'registerScripts\' ) );
}
public function registerScripts() {}
}
Since static::
references the calling class, this allows to write reusable classes for your plugins/themes, and kind of wrap up some of WordPress\' legacy ugliness.
For example, you could write an abstract class for custom post types like this:
namespace WordpressPlugin;
abstract class AbstractPostType {
const SLUG;
private function __construct() {}
public static function initialize() {
add_action( \'init\', array( static::class, \'registerPostType\' ), 0 );
add_action( \'init\', array( static::class, \'registerTaxonomies\' ), 1 );
add_action( \'add_meta_boxes\', array( static::class, \'addMetaBox\' ) );
}
public static function registerPostType() {}
public static function registerTaxonomies() {}
public static function addMetaBox() {}
}
Aftet that, you can now create custom post types without having to duplicate all of the boilerplate in each subclass, like this:
namespace WordpressPlugin;
class ExamplePostType extends AbstractPostType {
const SLUG = \'example-post-type\';
public static function registerPostType() {
register_post_type( self::SLUG, array(
...
) );
}
}