Monday, 29 June 2015

Understanding variables in PHP

PHP defaults to pass by reference instead of pass copy, What this means is that in older versions of PHP passing a variable to a function would have passed a copy of the variable to the function thus using x2 amount of memory.  PHP was updated to pass a reference as default which would only make a copy if you changed the variables content.  To pass an actual reference to a variable you would have to put the & symbol before your variable for example making the scope of the functions variable be external to the function.

fn(&$x);


The & represents the address of a variable;

a pointer is a number 0...n which when used in conjunction with software development represents a memory address.

so for example


$list = Array(...);


the variable $list holds an Array of information or in other words points to an area of memory

lets say that $list holds 1Mb of information but since that information is really a block of memory (1048576 bytes) and lets say that the first bit of information is in the memory address 1,000,000 and for the purpose of this conversation it is a solid block of memory with no fragmentation so the end point is (1000000+1048576) = 2,048,576

Since php now passes variables by reference

1 $results = fn($list );
2
3 function fn($val){
4 echo $val;
5 }


the variable $val is a pointer to the same memory space as $list and thus can be said to have a "reference" to the data. So what does this mean?

well instead of php having to have two variables $list & $val both containing 1Mb of data in memory at the same time (said to be a copy) we can pass a 32/64bit pointer which references the original value.

Now the interesting part if we added an additional line between 3&4

$val[count($val)] = 'woo';


this would cause php to make a complete copy of the data at that memory location and then change hte memory location that $val points to. Thus any changes to $val would not effect $list; as it is now a local variable to the function.

if you want changes to be applied the $list variable then change line one to be $result = fn(&$list);