Variable scope

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. For
example:

<?php$a = 1;include 'b.inc';?>

Here the $a variable will be available within
the included b.inc script. However, within
user-defined functions a local function scope is introduced. Any
variable used inside a function is by default limited to the local
function scope. For example:

<?php$a = 1; /* global scope */

function test(){ echo $a; /* reference to local scope variable */ }

test();?>

This script will not produce any output because the echo statement
refers to a local version of the $a variable,
and it has not been assigned a value within this scope. You may
notice that this is a little bit different from the C language in
that global variables in C are automatically available to
functions unless specifically overridden by a local definition.
This can cause some problems in that people may inadvertently
change a global variable. In PHP global variables must be
declared global inside a function if they are going to be used in
that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php$a = 1;$b = 2;

function Sum(){ global $a, $b;

$b = $a + $b;}

Sum();echo $b;?>

The above script will output 3. By declaring
$a and $b global within the
function, all references to either variable will refer to the
global version. There is no limit to the number of global
variables that can be manipulated by a function.

A second way to access variables from the global scope is to use
the special PHP-defined $GLOBALS array. The
previous example can be rewritten as:

The $GLOBALS array is an associative array with
the name of the global variable being the key and the contents of
that variable being the value of the array element.
Notice how $GLOBALS exists in any scope, this
is because $GLOBALS is a superglobal.
Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

<?phpfunction test_global(){// Most predefined variables aren't "super" and require // 'global' to be available to the functions local scope.global $HTTP_POST_VARS;

echo $HTTP_POST_VARS['name'];

// Superglobals are available in any scope and do // not require 'global'. Superglobals are available // as of PHP 4.1.0, and HTTP_POST_VARS is now // deemed deprecated.echo $_POST['name'];}?>

Note:

Using global keyword outside a function is not an
error. It can be used if the file is included from inside a function.

Using static variables

Another important feature of variable scoping is the
static variable. A static variable exists
only in a local function scope, but it does not lose its value
when program execution leaves this scope. Consider the following
example:

Example #4 Example demonstrating need for static variables

<?phpfunction test(){$a = 0; echo $a;$a++;}?>

This function is quite useless since every time it is called it
sets $a to 0 and prints
0. The $a++ which increments the
variable serves no purpose since as soon as the function exits the
$a variable disappears. To make a useful
counting function which will not lose track of the current count,
the $a variable is declared static:

Example #5 Example use of static variables

<?phpfunction test(){ static $a = 0; echo $a;$a++;}?>

Now, $a is initialized only in first call of function
and every time the test() function is called it will print the
value of $a and increment it.

Static variables also provide one way to deal with recursive
functions. A recursive function is one which calls itself. Care
must be taken when writing a recursive function because it is
possible to make it recurse indefinitely. You must make sure you
have an adequate way of terminating the recursion. The following
simple function recursively counts to 10, using the static
variable $count to know when to stop:

Example #6 Static variables with recursive functions

<?phpfunction test(){ static $count = 0;

$count++; echo $count; if ($count < 10) {test(); }$count--;}?>

Note:

Static variables may be declared as seen in the examples above.
From PHP 5.6 you can assign values to these variables which are the
result of expressions, but you can't use any function here, what will cause a parse error.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the
static and
global modifier
for variables in terms of
references. For example, a true global variable
imported inside a function scope with the global
statement actually creates a reference to the global variable. This can
lead to unexpected behaviour which the following example addresses:

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:<?phpfor($j=0; $j<3; $j++){ if($j == 1)$a = 4;}echo $a;?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:<?php//declare this before includeglobal $myVar;//or declare this inside the include file$nowglobal = $GLOBALS['myVar'];?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?phpfunction safeinclude($filename){//This line takes all the global variables, and sets their scope within the function:foreach ($GLOBALS as $key => $val) { global $$key; }/* Pre-Processing here: validate filename input, determine full path of file, check that file exists, etc. This is obviously not necessary, but steps I found useful. */if ($exists==true) { include("$file"); } return $exists;}?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course. In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().

To be vigilant, unlike Java or C++, variables declared inside blocks such as loops (for, while,...) or if's, will also be recognized and accessible outside of the block, the only valid block is the BLOCK function so:

In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

<?php

error_reporting(E_ALL);

$GLOB = 0;

function test_references() { global $GLOB; // get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB$test = 1; // declare some local var$GLOBALS['GLOB'] = &$test; // make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test

$GLOB = 2; // set new value to global variable via earlier set local representation, write to old address

echo "Value of global variable (via local representation set by keyword global): $GLOB <hr>";// check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)

global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $testecho "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";// check global variable via local representation => 1 (also value of local variable $test, new address was used) }

Sometimes a variable available in global scope is not accessible via the 'global' keyword or the $GLOBALS superglobal array. I have not been able to replicate it in original code, but it occurs when a script is run under PHPUnit.

PHPUnit provides a variable "$filename" that reflects the name of the file loaded on its command line. This is available in global scope, but not in object scope. For example, the following phpUnit script (call it GlobalScope.php):

Static variables do not hold through inheritance. Let class A have a function Z with a static variable. Let class B extend class A in which function Z is not overwritten. Two static variables will be created, one for class A and one for class B.

WARNING! If you create a local variable in a function and then within that function assign it to a global variable by reference the object will be destroyed when the function exits and the global var will contain NOTHING! This main sound obvious but it can be quite tricky you have a large script (like a phpgtk-based gui app ;-) ).

Take to heart this hard-won rule: Declare AT THE TOP any variable that is to be global. Both at the top of the FILE AND at the top of any FUNCTION where it appears.

Why AT THE TOP? So it is sure to be declared before use. Otherwise a non-global version of the variable will be created and your code will fail.

Why at the top of a FUNCTION? Because otherwise the function will refer only to its local version of the variable and your code will fail.

Why at the top of the FILE? Because someday--a day that you cannot now imagine--you will want to "include" the file. And when you do, instances of the variable outside functions will not go in the global scope and your code will fail. (When the "include" is inside a calling function, variables in the included file go into the scope of the calling function.)

There're times when global variables comes in handy, like universal read only resources you just need to create once in your application and share to the rest of your scripts. But it may become quite hard to track with "variables".

I was pondering a little something regarding caching classes within a function in order to prevent the need to initiate them multiple times and not clutter the caching function's class properties with more values.

I came here because I remembered something about references being lost. So I made a test to see if I could pull what I wanted to off anyway. Here's and example of how to get around the references lost issue. I hope it is helpful to someone else!

This is probably obvious to most people, but global always refers to the variable in the global (top level) variable of that name, not just a variable in a higher-level scope. So this will not work:<?php

// $var1 is not declared in the global scope

function a($var1){

function b(){ global $var1; echo $var1; // there is no var1 in the global scope so nothing to echo

Note that if you declare a variable in a function, then set it as global in that function, its value will not be retained outside of that function. This was tripping me up for a while so I thought it would be worth noting.

i found out that on any (still not found) reason the <?php static $val =NULL; ?> is not working when trying to extract the data form the $var with a while statmente.g.:<?phpfunktion get_data() {static $myarray = null; if($myarray == NULL) {//get some info in an array();$myarray = array('one','two'); } while(list($key,$val) = each( $myarray ) ) {// do somethingecho "x: $key , y: $val"; }}?>when using foreach($myarray AS $key => $val) { .... instad of while then i see the result!

Quick tip for beginners just to speed things up:
If you have a bunch of global variables to import into a function, it's best to put them into a named array like $variables[stuff].
When it's time to import them you just so the following;

If you use __autoload function to load classes' definitons, beware that "static local variables are resolved at compile time" (whatever it really means) and the order in which autoloads occur may impact the semantic.

and two separate files A.php and B.php:class A extends Singleton{}class B extends A{}

then depending on the order in which you access those two classes, and consequently, the order in which __autoload includes them, you can get strange results of calling B::get_instance() and A::get_instance().

It seems that static local variables are alocated in as many copies as there are classes that inherit a method at the time of inclusion of parsing Singleton.

Using $GLOBALS inside a function you can override all references to global variables in that function with variables passed into the function as arguments. This is useful when a function does stuff to a global object but you sometimes want it to do that stuff to a different object, and you don't want to rewrite any code.

For example, suppose there's a global object called $user that refers to the currently-logged-in user and a function that does stuff to that user object:

<?phpfunction example_function() { global $user;

// do stuff with the objectecho $user->id;}?>

Here's how you can make that function optionally do stuff to a different user object:

If you are used to include files which declare global variables, and if you now need to include these files in a function, you will see that those globals are declared in the function's scope and so they will be lost at the end of the function.

//Let's extract the variables that were defined AFTER the call to 'eval'$function_variable_names = array("function_variable_names" => 0, "before_eval_vars" => 0, "created" => 0);//We can generate a list of the newly created variables by substracting the list of the variables of the function and the list of the variables which existed before the call to the list of current variables at this point$created = array_diff_key(get_defined_vars(), $GLOBALS, $function_variable_names, $before_eval_vars);//Now we globalize themforeach ($created as $created_name => $on_sen_fiche) global $$created_name;//And we affect themextract($created);

The work-around is of course changing the assignment in the constructor to a reference assignment as such:

<?php
//....
$this->val = &var;
//....
?>

If the global you're setting is an object then no reference is necessary because of the way PHP deals with objects. If you don't want to reference to the same object however you can use the clone keyword.

<?php
//...
global $Obj;
$this->obj_copy = clone $Obj;
//...
?>

[EDIT BY danbrown AT php DOT net: Merged all thoughts and notes by this author into a single note.]

PHP 5.1.4 doesn't seem to care about the static keyword. It doesn't let you use $this in a static method, but you can call class methods through an instance of the class using regular -> notation. You can also call instance methods as class methods through the class itself. The documentiation here is plain wrong.

While designing a database access class, I needed a static variable that will be incremented for all instances of the class each time the class connected to the database. The obvious solution was to declare a "connection" class variable with static scope. Unfortunatly, php doesn't allow such a declaration.So I went back to defining a static variable in the connect method of my class. But it seems that the static scope is not inherited: if class "a" inherit the "db access" class, then the "connection" variable is shared among "a" instances, not among both "a" AND "db access" instances. Solution is to declare the static variable out of the db access class, and declare "global" said variable in the connect method.

If you include a file from within a function using include(), the included file inherits the function scope as its own global scope, it will not be able to see top level globals unless they are explicit in the function.

I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me:

Some people (including me) had a problem with defining a long GLOBAL variable list in functions (very error prone). Here is a possible solution. My program parses php file for functions, and compiles GLOBAL variable lists. Then you can just remove from the list those variables which need not be global.

Every call to the function Test() is a differenct SCOPE and therefore the static declarations and initializations are NOT executed again. So what Im trying to say is that its OK to declare and initialize a static variable multiple times if you are in one function... but its NOT OK to declare and initialize a static variable multiple times if you call that same function multiple times. In other words the static variable is set once you LEAVE a function (even if you go back into that very same function).

It's possible to use a variable variable when specifying a variable as global in a function. That way your function can decide what global variable to access in run-time.

<?php
function func($varname)
{
global $$varname;

echo $$varname;
}

$hello = "hello world!";
func("hello");
?>

This will print "hello world!", and is roughly the same as passing by reference, in the case when the variable you want to pass is global. The advantage over references is that they can't have default parameters. With the method above, you can do the following.