4

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');

1 Answer 1

6

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'));
4
  • Is this really required? Shouldn't PHP always pass a reference to that function anyway? Sep 2, 2011 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, 2011 at 16:06
  • 2
    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.
    – Roman
    Sep 2, 2011 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, 2011 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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