What does the "&" sign mean in PHP?

I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.

//Actions and Filters
if (isset($dl_pluginSeries)) {

    //Actions
    add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
    //Filters
    add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:

$a = 1;

function inc(&$input)
{
   $input++;
}

inc($a);

echo $a; // 2

Objects will be passed by reference automatically.

If you like to handle a copy over to a function, use

clone $object;

Then, the original object is not altered, eg:

$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

Solution 2

The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.

See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/

Solution 3

This passes something by reference instead of value.

See:

http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php

Solution 4

I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don’t need to return the function to the return value and set the new value to my variable.

Example

function fixString(&$str) {
    $str = "World";
}

$str = "Hello";
fixString($str);
echo $str; //Outputs World;

Code without the &

function fixString($str) {
    $str = "World";
    return $str;
}

$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply