Search code examples
phpwordpressreference

&$this in Wordpress add_action callback


I'm just getting my feet wet in Wordpress, and I'm trying to write a very simple plugin using OOP techniques. I've been following this tutorial: http://www.yaconiello.com/blog/how-to-write-wordpress-plugin/ . So far I feel like I understand most of what's going on, but I'm slightly puzzled by statements such as this one:

add_action('init', array(&$this, 'init')); 

Having read the documentation on Wordpress's add_action() and PHP callables, I gather that the second argument is a method of a class instance. But I don't understand why $this has to be passed by reference.

Found this note in the PHP docs about callables which I suspect may have something to do with it, but I'm still having a hard time wrapping my head around what the difference is:

Note: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

If I have PHP 5, am I safe just using array($this,'init')?

Possibly related: add_action in wordpress using OOP?


Solution

  • Yes - you are safe to just use array($this, 'init');.

    What this actually is, is a "callable" in PHP. It will be invoked using call_user_func() or call_user_func_array() (internally inside the add_action method).

    PHP's official description of this type of callable:

    A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

    You can read more about callables here.