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.

Why, Where, and When to use reference pointers in filters/hooks? What are the potential cons of not using them when suggested or required? Just looking for a more detailed answer than the codex provides and maybe some real world applications of this.

For example: add_filter('some_wp_filter', array(&$this, 'my_function_to_filter');

share|improve this question
add comment

1 Answer 1

up vote 6 down vote accepted

The example you give is used when you're building a plugin/theme using a class.

In normal use, your functions.php file would just have:

function my_function_to_filter( $args ) {
    // ... function stuff here
    return $args;
}
add_filter('some_wp_filter', 'my_function_to_filter');

If you're using a class, though, things would look different. You'd likely have a my-class.php file containing:

class My_Class {
    function my_function_to_filter( $args ) {
        // ... function stuff here
        return $args;
    }
    add_filter('some_wp_filter', array(&$this, 'my_function_to_filter'));
}

In this case, &$this is passing in a reference to the class so that the filter called is the my_function_to_filter function in the current class. You can also do this with static methods if you want to keep your filter calls all in the same place.

So in my-class.php you'd have:

class My_Class {
    static function my_function_to_filter( $args ) {
        // ... function stuff here
        return $args;
    }
}

And in functions.php or your core plugin file you'd have:

add_filter('some_wp_filter', array('My_Class', 'my_function_to_filter'));
share|improve this answer
    
Is this really required? Shouldn't PHP always pass a reference to that function anyway? –  onetrickpony Sep 2 '11 at 15:55
    
This is how the filter/action system handles naming collisions. If you pass the class containing the function, you can have several classes defining function my_finction_to_filter(){} without any conflicts. Remember, you're passing a ref to the class so that it's stored in the action/filter's lookup table for later when WP calls apply_filters()/do_action(). –  EAMann Sep 2 '11 at 16:06
    
Excellent answer. Thank you EAMann. –  hsatterwhite Sep 2 '11 at 18:15
1  
Just a side note: Since PHP5 the default behavior is to pass objects by reference. The & before the $this reference is only required for backwards compatibility. –  rofflox Sep 2 '11 at 20:40
    
@Roman - Good point. A lot of us merely add the & out of force of habit. But if you're specifying static for functions, you're already in PHP5 territory ... –  EAMann Sep 2 '11 at 20:54
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.