Variable scope (as defined here)
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
//a.php
<?php
class a {
function &func () {
$avar = array("one", "two", "three");
return $avar;
}
?>
__
//b.php
<?php
class b {
include("a.php");
$ainstance = new a;
var_dump($ainstance->func());
}
?>
The above code will Dump information about the variable as expected (I mean WRT the structure as formed in the function func).
My doubt is that,
- where are the variable stored when it is in the scope of a function?
- If it is on the call stack, then wont the variable be cleaned/destroyed when the function terminates?
- Since the variable is not getting destroyed (as per the code above), why is it not getting destroyed or does PHP have a mechanism to save the variable (say in a heap)and return the reference to it.
- Does PHP have call stack at all?
All variables in PHP are
zval*, that is, C pointers.If you return by value, PHP will, in most cases, automatically copy the
zval*and return that. If you return by reference, PHP will return the originalzval*. In none of these cases does the returnedzval*refcount reaches 0.On the C side, well, when you return a variable, it returns a pointer to a
zval, which is a C struct containing information about the variable (namely type, value, the refcount and ais_refflag).Since it’s a pointer, it’s not actually returning a local C variable, but a pre-allocated
zvalpointer, which points to the location of the actualzval. Unless thatzval*refcount reaches 0 (i.e.: not storing the return value), the variable will still live until the end of the program.