PHP Variable Scope in Functions

In this chapter you will learn:

  1. What is the scope of a variable
  2. Example - variable scope

Description

Variables declared outside of functions and classes are global. global variables are available else where in the script.

Function variables are self-contained and do not affect variables in the main script.

Variables from the main script are not implicitly made available inside functions.

Example

Take a look at this example:


<?PHP//from j  a v a 2s . c  o m
function foo() { 
   $bar = "java2s.com"; 
} 
$bar = "PHP"; 
foo(); 
print $bar; 
?>

The code above generates the following result.

Execution of the script starts at the $bar = "PHP" line, and then calls the foo() function.

foo() sets $bar to java2s.com, then returns control to the main script where $bar is printed out.

Function foo() is called, and, having no knowledge that a $bar variable exists in the global scope, creates a $bar variable in its local scope.

Once the function ends, all local scopes are gone, leaving the original $bar variable intact.

Next chapter...

What you will learn in the next chapter:

  1. What is PHP global variable
  2. How to create a global variable
  3. Example
  4. Example - $GLOBALS Array
  5. Note for global variables
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable