PHP: What is the & Ampersand Preceding Variables

Well, this one is hard to find on Google, so I’m putting it in WhyPad to make it easy to find…at least for me, and I guess for you too since you here. Welcome! You may see PHP code snippets (PHP 5+ only) that have an ampersand, ‘&’, preceding a variable like &$my_variable. So, what does it do? It sets up a reference to the original variable instead of copying it’s value. The following snippet demonstrates:

$original = "foo";
&$ref = $original;

echo $ref;   \\Prints  "foo"....Note that you don't continue to use the '&' after the var is initialized

now change $original

$original = "bar";

echo $ref;  \\Now prints:  "bar"

$ref would be unaffected by changes to $original if it had been set using the normal: $ref = $original;

Next to figure out what that @ is doing in PHP code… ;-)

[UPDATE] David sheds light on the “@” below…Thanks David!

Cheers,
Byron

Filed under: PHP

Comments

  1. David Says:

    Hah, thanks for reminding me about what the “&” does. Hadn’t used it in such a long time I’d forgotten.

    As for the “@”, it’s used for operators and functions to tell PHP not report any errors if they should occur. A good example is if you want to delete a file - should that file not exist, PHP would return the error message saying that.

  2. byron Says:

    David,
    Thanks for dropping by! And thanks for the note on “@”. I keep forgetting these little details since I don’t use them very often.

    Byron

  3. Jary Says:

    hi im using php 5.x and im getting error whenever i try to use &$ref..pls help thanks

  4. byron Says:

    Hi Jary,

    Here are some alternative methods to try:

    $new_var =& $old_var;

    or if passing through a function

    function my_fun(& $old_var){

    }

    If those don’t work, post your code and I’ll take a look.

    Regards,
    Byron

Leave a Reply