Hate Posted September 18, 2010 Share Posted September 18, 2010 Hi, I've seen code like this multiple times, but I don't really know what it means. function funcName(&$something) { // whatever } What exactly does the "&" do before the variable? Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted September 18, 2010 Share Posted September 18, 2010 These explain it pretty well. (Better than I could, at least) http://www.whypad.com/posts/php-what-is-the-ampersand-preceding-variables/193/ http://www.phpreferencebook.com/samples/php-pass-by-reference/ Quote Link to comment Share on other sites More sharing options...
Andy-H Posted September 18, 2010 Share Posted September 18, 2010 When you pass a variable to a function, it's value is copied to a variable in the local scope of the function, so in order for the functions effect to take place in global scope, you would have to return the variable and assign it as an rvalue to a variable in global scope. The & operator passes a reference of the variables memory location to the function, so any changes made to that variable within the scope of the function, take effect on the same variable in global scope. Try this: $var = 'Hello'; echo 'Global scope $var: ' . $var . '<br /><br />'; function world(&$var) { $var .= ' World!'; } function wrongWorld($var) { $var .= ' World!'; echo 'Function scope $var: ' . $var . '<br />'; } wrongWorld($var); echo 'Global scope $var: ' . $var . '<br />'; word($var); echo 'Global scope $var after reference: ' . $var . '<br />'; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.