Global and Static Variables – Scope in PHP Functions

PHP

When you want to use variables outside your function for use within your function, you will have to use the keyword global. This will allow you to use variables declared outside of a function. It will even override the variables inside the function if they have the same name. You can also use it to access the variables inside the function from outside.

Global Variables

Using variables inside a function

Example:

<?php
$name = "Chris";
function hello($greeting,$name){
  global $name;
  $output = $greeting." ".$name;
  return $output;
}
echo hello("Good Morning","Ashish");
?>
Output:
Good Morning Chris

Note: The value for the variable $name = Chris is used inside the function hello() because we declared it as global. The argument passed for the same variable $name is ignored or overridden.

Using Variables Outside a Function

Example:

<?php
function hello($name){
  global $output;
  $output="Good Morning ".$name;
}
hello("Ashish");
echo $output;
?>
Output:
Good Morning Ashish

Using $GLOBALS

If you prefer, you can use $GLOBALS instead of the keyword global. Here’s how you do it.

Example:

<?php
$name = "Ashish";
function hello($greeting){
  $GLOBALS['output'] = $greeting." ".$GLOBALS['name'];
}
hello("Good Morning");
echo $output;
?>
Output:
Good Morning Ashish
Notes:

  1. We used $GLOBALS to acces the variable $name declared outside the function.
  2. Again $GLOBALS[‘output’] is used so that the variable name $output is accessible outside the function. When you do this, there’s no need to return a value from the function itself.

Static Variables

Static variables are used so as to retain the values of variables even after a function is called. When a function is called for the second time, the changed value is not saved. So, to ensure that the value is saved, we use static variables.

Example:

<?php
function add($value){
static $total;
$total=$total+$value;
echo $total;
}
add(10);
echo "<br />";
add(2);
echo "<br />";
add(13);
?>

Output:

10
12
25
Note: See how the value for the variable $total is retained every time the function is called.