1

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?
0

1 Answer 1

4

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 original zval*. In none of these cases does the returned zval* 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 a is_ref flag).

Since it's a pointer, it's not actually returning a local C variable, but a pre-allocated zval pointer, which points to the location of the actual zval. Unless that zval* refcount reaches 0 (i.e.: not storing the return value), the variable will still live until the end of the program.

Sign up to request clarification or add additional context in comments.

2 Comments

Although I haven't understood it. Will go through zval. +1 for pointing to zval.
What you need to know is that when returning variables, PHP automatically returns a copy of the variable, unlike C per example, in which you have to make a copy yourself (e.g.: when returning a C string).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.