Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me understand PHP variable references and scope

References:

  1. If I pass a variable to a function (e.g. $var), is that supposed to be a copy of a reference to the actual variable (such that setting it null doesn't affect other copies)?
  2. Or is it receiving a reference to what is a new copy of the actual variable (such that setting it to null destroys its copy only)?
  3. If the latter, does this copy objects and arrays in memory? That seems like a good way to waste memory and CPU time, if so.

I think can understand passing by reference (e.g. &$var) correctly by knowing how this works, first.

Scope:

  1. What's the deal with local scope? Am I right in observing that I can declare an array in one function and then use that array in other functions called within that function WITHOUT passing it to them as a parameter?
  2. Similarly, does declaring in array in a function called within a function allow it to be available in the caller?
  3. If not, does scoping work by a call stack or whatever like every bloody thing I've come to understand about programming tells me it should?

PHP is so much fun. :(

like image 531
Hamster Avatar asked Jan 20 '11 16:01

Hamster


1 Answers

If I pass a variable to a function (e.g. $var), is that supposed to be a copy of a reference to the actual variable (such that setting it null doesn't affect other copies)?

Depends on the function. And also how you call it. Look at this example: http://www.ideone.com/LueFc

Or is it receiving a reference to what is a new copy of the actual variable (such that setting it to null destroys its copy only)?

Again depends on the function

If the latter, does this copy objects and arrays in memory? That seems like a good way to waste memory and CPU time, if so.

Its going to save memory to use a reference, certainly. In php>4 it always uses reference for objects unless you specify otherwise.

What's the deal with local scope? Am I right in observing that I can declare an array in one function and then use that array in other functions called within that function WITHOUT passing it to them as a parameter?

No you can't.

Similarly, does declaring in array in a function called within a function allow it to be available in the caller?

No, it doesn't.

If not, does scoping work by a call stack or whatever like every bloody thing I've come to understand about programming tells me it should?

If you want to use a variable from outside the function, before using it, you'd write global $outsidevar

like image 130
profitphp Avatar answered Oct 02 '22 17:10

profitphp