PHP: What is the & Ampersand Preceding Variables
Posted on Friday, June 6th, 2008. Filed under PHP.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
You can now:
Read Comments (4). Or, Leave A Trackback. Or, view Comments Feed.Previous Post: Automated Testing SAP with Worksoft Certify - Reviewed »
Next Post: Wordpress Plugin: BWB-ReWriter for Custom URL Rewriting »
4 Responses to “PHP: What is the & Ampersand Preceding Variables”
Leave a Reply
Note: Any comments are permitted only because the site owner is letting you post, and any comments will be removed for any reason at the absolute discretion of the site owner.You must be logged in to post a comment.












June 8th, 2008 07:11
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.
June 8th, 2008 13:01
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
July 11th, 2008 22:25
hi im using php 5.x and im getting error whenever i try to use &$ref..pls help thanks
July 12th, 2008 10:14
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