How to use PHP Variable Scope

In this article I am going to explain PHP variable scope.
  • 1399

Use PHP Variable Scope

The variable scope is the part of the script in which the variable can be referenced.

PHP have four different variable scopes:

  • Local
  • Global
  • Static
  • Parameter

Local Scope

A PHP variable declared within a PHP function.

Example

<?php
$a = 5; // global scope

function myTest()
{
echo $a; // local scope
}

myTest();
?>

Local variables are deleted as soon as the function is completed.

Global Scope

A PHP variable declared within a PHP function.

Example

<?php
$a = 5;
$b = 10;

function myTest()
{
global $a, $b;
$b = $a + $b;
}

myTest();
echo $b;
?>

This array is also accessible from within functions and can be used to update global variables directly.

Static Scope

A PHP variable declared within a PHP function.

Example

static $rememberMe;

The variable is still local to the function in static scope.

Parameter Scope

A PHP variable declared within a PHP function.

Example

function myTest($para1,$para2,...)
{
// function code
}

Parameters are also called arguments. We will discuss them in more detail when we talk about functions.

You may also want to read these related articles :here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2013 dotNetheaven. All rights reserved.