Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ()
       {
            //....................

                $this->top_page_hook();
            //....................
        } 

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

        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
add comment

1 Answer

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
add comment

Your Answer

 
discard

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.