Global Objects and Public Methods

This is not common practice, but it works. A better approach, is to use a class and with the singleton pattern, just like WooCommerce and many others, where you have:

  • A static function (called instance, getInstance…) that:
    • Creates an instance (object) if not already done and returns it
    • Or returns the existing instance

Let’s continue with the WooCommerce example; we used to do this to access the global object:

global $woocommerce; 

Now we do:

WooCommerce::instance();

# Or with the handy Shortcut
WC();

I think you will enjoy reading these:


You can check the value of current_filter() inside your method, but if I were you, I wouldn’t bother. This is not a threat, and other developers may want to use your code, so don’t block them.

Leave a Comment