[wp-hackers] Passing class methods by reference

Michael D Adams mda at blogwaffe.com
Thu Aug 5 18:57:05 UTC 2010


On Thu, Aug 5, 2010 at 11:21 AM, Andrew Nacin <wp at andrewnacin.com> wrote:
> class my_class {
>   function __construct() {
>     add_action( 'init', array( &$this, 'init' ) );
>   }
>   function init() {}
> }
> $my_class_instance = new my_class;
> remove_action( 'init', array( $my_class_instance, 'init' ) );
>
> This is generally why I always assign instantiations to a variable in my
> plugins (versus simply calling `new myclass;`), that way I'm playing nice
> with others and allowing another plugin to modify the callbacks I attach.

Off topic: I have an irrational hatred of globals.  I'm on a twelve
step program and everything.

What I usually do is offer to plugins some static method on my classes
to accomplish the same thing.  In a case like this where you're using
my_class as a singleton, it's pretty straightforward.

require 'wp-load.php';

class My_Class { // Nacin should ucwords() his classes :)
        static $instance;
        static function &instance() {
                // You could use a static variable here instead
                if ( !self::$instance )
                        new My_Class;
                return self::$instance;
        }

        function __construct() {
                self::$instance =& $this;
                add_action( 'shutdown', array( &$this, 'hola' ) );
        }

        function hola() {
                die( "Hola.  If you see this, this example is broken.\n" );
        }
}

My_Class::instance();

function adios() {
        remove_action( 'shutdown', array( My_Class::instance(), 'hola' ) );
}

adios();


Static class methods are slow, though.


More information about the wp-hackers mailing list