markjaquith / feedback

Ask @markjaquith anything!
42 stars 4 forks source link

Class methods/functions: to call by reference or not #1

Closed MickeyKay closed 10 years ago

MickeyKay commented 10 years ago

I notice that different plugins seem to do things differently when calling class methods/functions within the class.

Some pass the class instance by reference, like so: add_action( 'init', array( &$this, 'load_plugin_textdomain' ) );

And some don't: add_action( 'init', array( $this, 'load_plugin_textdomain' ) );

Can you give any input on the advantages/disadvantages of one vs. the other?

Thanks!

markjaquith commented 10 years ago

The &$this version is a relic from PHP 4, to force the passing of the object by reference, instead of a copy of the object. In PHP 5, the handling of passing objects changed, so this is no longer necessary (in fact, it is recommended that you don't do it).

Since PHP 4 is a thing of the past, you can and should just do array( $this, 'method_to_call' ).

http://www.php.net/manual/en/language.oop5.references.php