wnelson Posted January 20, 2012 Share Posted January 20, 2012 Hello all, I'm a PHP newbie, so please pardon me if this question has already been asked somewhere in this forum. I have been reading the PHP documentation. On this page http://www.php.net/manual/en/language.references.pass.php, I came across this code: <?php ... snip ... function &bar() { $a = 5; return $a; } foo(bar()); ?> This is returning a reference to local variable $a. Coming from a C/C++ background, my intuition tells me this just shouldn't work, since the local variable $a should be deleted as soon as the function "bar" returns. The code seems to work, though. My guess is that PHP is basically ref-counting and garbage collecting local variables like $a, and so it will not be automatically cleaned up on call exit. Is this about right? Thanks! WN Quote Link to comment https://forums.phpfreaks.com/topic/255415-returning-reference-to-local-variable/ Share on other sites More sharing options...
RussellReal Posted January 20, 2012 Share Posted January 20, 2012 Okay, I don't believe that this functionality gives you a reference to that specific variable in its localscope.. I believe it is returning A REFERENCE to the variable, and bringing it out into the global scope. And then all of the other local scope variables, are destroyed once the function ends.. the example PHP gives you, on that page, is a good example, because if the function wasn't returning a reference to a variable, you would only have the number contained within the other variable, not the variable reference contained in the other variable.. the reason the PHP example is good is because.. EXAMPLE A function abc() { $a = 5; return $a; } in the above context, when it returns $a, it will be evaluated prior to the return and it will only return the value 5.. but with this function: EXAMPLE B function &abc() { $a = 5; return $a; } it will return $a, not 5, but $a equates to 5.. but it gives you slightly more control over the variable $a, and slightly more options.. in example A, if you were to do this: function xyz(&$abc) { return ++$abc; } $x = ayx(abc()); it would most likely cause an error, as you're not supposed to pass non-variables as references.. but in example B the above code would prolly work just fine now, this seems a little retarded to do all of this to get the same outcome as you could get with probably the same or less amount of text, but in an OBJECT, it seems more likely to need this functionality.. but, I've never used this, and I'm a professional developer, so honestly, its not too important Quote Link to comment https://forums.phpfreaks.com/topic/255415-returning-reference-to-local-variable/#findComment-1309518 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.