WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have been trying to write a reusable modular options class and I am stuck at this specific point.

How do i define hooks within php classes?

Try 1 :

class super_options {
     // ..........................

       function render_options_page ()


     // ..........................

        function top_page_hook() {
             do_action( array( &$this, 'top_page_hook') );


and when hooking to the above, add_action( array( &$plugs, 'top_page_hook' ), 'stuff_for_top_hook' );

This doesn't work.

Try 2 :

  • Replacing the $this->top_page_hook();, with do_action( 'top_page_hook' );
  • Calling add_action( 'top_page_hook', 'stuff_for_top_hook' );
  • Works, but the class loses its reusability.

So how do i take care of this? Please share your wisdom. Thanks.

share|improve this question
up vote 2 down vote accepted

Hook can only be identified by string. So the only option to have dynamic hook is is use some variable(s) in its name:

do_action( $some_string_variable . '_top_page_hook' );

Depending on what you are trying to do this can be something meaningful (like prefix, defined by configuration) or something randomly generated to be unique ID (not so common).

share|improve this answer
Exactly. You only pass in the class when you call add_action() so you can avoid name collisions with function names. do_action() just takes the string name for the action (well, and additional variables you're passing along, but that's beyond the scope of your question). – EAMann Aug 26 '11 at 21:30
That works perfectly. I already have a property $this->page_prefix, so $this->page_prefix . '_top_page_hook' does the job. Thanks a lot. – OpenOne Aug 26 '11 at 21:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.