Why, Where, and When to use reference pointers in filters/hooks?

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

Related posts

Leave a Reply

1 comment

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