Hello, is the returning values for reference method in php for editing the returned value externally from the function?
Does this code modify the value of the $contatore returned by funzione and add the value in $a to it? Why does it add instead of overwrite it?
Sorry for my questions, but I can't understand these concepts
Thank you!
Yes and no. What happens here is the result of the variable created within the function is assigned by reference outside of the function. So the dynamic memory is converted to heap and assigned to static.
PHP Code:
function &increment() { static $increment = 0; return ++$increment; }
Changes in my $increment variable will reflect in any variable assigned by reference to the result of the increment() function. Changes in any variable assigned by reference to the result of the function will reflect across all variables assigned by reference since it changes the $increment variable.
The only actual purpose I've found this useful for was for templating that included a end call to the execution time and number of queries. Since the templates were also queried, in order to get the right count including the template, I had to return by reference the value of my db class' query count.
This does call the function: $a = &increment();. So of course you will get the behaviour of the function running. This of course will never work, since function calls cannot be the lhs of an expression: &increment() = 3;.
$increment is called within the function, and since its static it retains its previous state.
You cannot access a variable created within a function. That is what scope is all about, so $increment will never be directly available. But since you return by reference and assign by reference to $a and $b, you can modify the value of $increment by modifying one of $a or $b.