If you’ve worked with PHP a bit, you may have seen someone put an ampersand (“&”) in front of a variable, like this:
add_action('admin_print_scripts', array(&$this,'admin_scripts'));
In this example, we’re using a WordPress hook, and passing an array with a class and method combination, instead of just a function name. (The $this
variable, of course, means that the function name is inside the same class.) But what does the ampersand before the variable mean, though? To tell you the truth, I didn’t know until recently…
When you prefix a variable with an ampersand, you’re creating a “reference.” PHP references are like shortcuts or symlinks on your computer. You can create a pointer variable that is just another name for the same data.
$variable = 'Lorem ipsum'; $new = &$variable; $variable = 'Some new data'; echo $new; //Prints "Some new data"
Pretty nifty. I’m sure you can think of some uses for that.
In the WordPress hook example, what I gather to be happening is that the plugin author was passing a reference to the $this variable, rather than the variable itself. I assume there is some sort of RAM/CPU-saving benefit to this.