[wp-hackers] add_action arrays?

Otto otto at ottodestruct.com
Wed Sep 23 16:26:40 UTC 2009


Important note: It's for when you use a class method as the callback,
*from inside the class itself*.

This is because $this references the object that you're currently in.

class PluginClass {
   function PluginClass() {
      add_action( 'some_action_hook', array( &$this, 'some_function' ) );
   }
   function some_function() {
      // whatever
   }
}
$plugin_object = new PluginClass();


That will work fine. But if you tried something like this:

class PluginClass {
   function some_function() {
      // whatever
   }
}
$plugin_object = new PluginClass();
add_action( 'some_action_hook', array( &$this, 'some_function' ) );

Then you'll have a problem, because $this makes no sense in that context.

You could do this instead:
add_action( 'some_action_hook', array( &$plugin_object, 'some_function' ) );

But that's bad practice. Better to let the class itself do its own
setup on instantiation.

-Otto



On Wed, Sep 23, 2009 at 7:14 AM, John Blackbourn
<johnbillion+wp at gmail.com> wrote:
> It's for when you use a class method as the callback. The first item
> in the array is a reference to the class, the second to the method.
>
> 2009/9/23 Thomas Belknap <dragonfly at dragonflyeye.net>:
>> I've seen a few plugins and bits of code internal to WordPress use the
>> following convention:
>>
>> add_action('pre_get_posts', array(&$this, 'postFilter'));
>>
>> But this usage is not documented anywhere? I attempted to use the same
>> convention and got the following error:
>>
>> call_user_func_array() [function.call-user-func-array]: First argument
>> is expected to be a valid callback, 'Array' was given in blah, blah,
>> blah...
>>
>> I was looking at the code for add_action and add_filter, and they
>> definitely seem to not take arrays into account as far as I can tell.
>> Is this a deprecated way of doing things? Is there some other way to
>> hook an object method into an action or filter?
>>
>> Thanks!
>> _______________________________________________
>> wp-hackers mailing list
>> wp-hackers at lists.automattic.com
>> http://lists.automattic.com/mailman/listinfo/wp-hackers
>>
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list