[wp-hackers] Passing class methods by reference

Mike Schinkel mikeschinkel at newclarity.net
Thu Aug 5 18:51:46 UTC 2010

On Aug 5, 2010, at 2:16 PM, scribu wrote:
> Might want to read this:
> http://stackoverflow.com/questions/1261764/wordpress-need-help-with-remove-action/1268992#1268992

Thanks!  I see you answered it (and I just voted it up.)  Good job. :)

> This is generally why I always assign instantiations to a variable in my
> plugins (versus simply calling `new myclass;`), that way I'm playing nice
> with others and allowing another plugin to modify the callbacks I attach. I
> believe I mention this as good practice in <
> http://www.andrewnacin.com/2010/05/11/in-wordpress-prefix-everything/>.

Thanks.  So if a plugin did not create an instance then it's pretty much not possible to remove the hooks they add, correct?

Okay, so here comes another question tangentially related question.  I see a lot of people using classes for plugins and initializing them as plugins but try as I might I can't see the benefit of doing that over using static class methods. So in your example I would have written it as:

class my_class {
  static function on_load() {
    add_action( 'init', array( __CLASS__, 'init' ) );
  static function init() {}

remove_action( 'init', array( 'my_class', 'init' ) );

The reason I chose this design pattern over using class instances include:

1.) it only adds one global symbol, i.e. only the class name and not a global variable too.
2.) There's no benefit to using instances (that I've identified) when the methods are used for hooks; we only need a "singleton."
3.) Using this pattern the plugin user can easily remove filters without me having (to remember to) define a variable in the global namespace.

So, the questions are:

1.) Am I missing something here why it might be preferable to use an instance rather than a class?
2.) If I'm not missing something why have we not promoted the pattern above rather than the instance equivalent (other than it just not occurring to people?)



More information about the wp-hackers mailing list