&$this

Take a look at this code, found inside a PHP class or object:

add_action( &$this, 'functionname' );

This looks familiar, and can be found in many themes and plugins. But what’s wrong with it? It’s PHP4 code in a PHP5 world.

General PHP rule for add_action:

When creating a callable, never use &$this, use $this instead

There is almost never a valid reason to use &$this in PHP, and there is never, under any circumstance, a valid need to use it in any WordPress API. WordPress requires PHP 5 as a minimum, and will not run on PHP4, so there is no reason to be PHP4 compatible.

But What Could Go Wrong?

Sure it’s not the best but better to be safe than sorry? Lets carry on and when we need to change, lets change

– someone who later went out of business

To understand why this is bad, we need to understand what changed between PHP 4 and 5.

In PHP 4, objects were passed by value. For example:

$a = new MyObject();
$b = $a;

In PHP 5, $a and $b are the same object. The variables point to an object we created, the same object. The variables store a reference to that object, and when we assign or pass the object around, we pass it via reference. This is similar to objects in Java, or pointers in C++.

In PHP 4 however, objects and variables are passed by value, not reference. When you run the above code in PHP 4, you get 2 objects, not 1. $b = $a; copies the object from $a to $b. This is because in PHP 4, $a doesn’t reference an object, $a is an object.

So when we call add_action in WordPress in PHP 4, your object isn’t hooked into a filter/action. Instead a copy of your object is hooked into that filter/action. To get around this, &$this is used. This is unnecessary in PHP 5.

This kind of logic worked in a PHP 4 world but has consequences in a PHP 5 world. For example, the same reasoning was used to pass objects and arrays as function arguments, but this can cause strict warnings and fatal errors in newer versions of PHP ( notably PHP 5.3 and beyond ).

Further Reading

7 thoughts on “&$this

  1. Pingback: $this vs &$this

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.