Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Variables Scope

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable refers to the section of the script where it can be accessed or used.

PHP has three distinct variable scopes:

  • Local
  • Global
  • Static

Global and Local Scope

A variable declared outside of a function has a GLOBAL SCOPE and can only be accessed from outside that function.

Example

Variable with global scope:

$x = 5; // global scope
function myTest() {
 // using x inside this function will generate an error
 echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";

A variable declared within a function has a LOCAL SCOPE and can only be accessed inside that function.

Example

Variable with local scope:

function myTest() {
 $x = 5; // local scope
 echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
You can have local variables with the same name in different functions since local variables are only recognized within the function where they are declared.

PHP The global Keyword

The global keyword allows you to access a global variable from within a function.

To do this, simply use the global keyword before the variable names inside the function:

Example

$x = 5;
$y = 10;
function myTest() {
 global $x, $y;
 $y = $x + $y;
}
myTest();
echo $y; // outputs 15

PHP also stores all global variables in an array called $GLOBALS[index], where the index corresponds to the variable name. This array is accessible from within functions and can be used to update global variables directly.

The previous example can be rewritten as follows:

Example

$x = 5;
$y = 10;

function myTest() {
 $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15

PHP The static Keyword

Typically, when a function completes execution, all of its variables are deleted. However, there are times when you may want a local variable to persist for future use.

To achieve this, use the static keyword when initially declaring the variable:

Example

function myTest() {
 static $x = 0;
 echo $x;
 $x++;
}

myTest
();
myTest();
myTest();

Then, each time the function is called, that variable will retain the information it had from the previous call.

Note: The variable remains local to the function.