PHP Variable Scope

PHP variable scope is the context which the php variable has been defined or the part where the variable can be used.

Always ,php variables can be declared in any part of the  script

Three PHP variable scopes:

  • Local variable
  • global variable
  • static variable

 

Global Variable are the ones that are defined outside a function and they are only accessible outside the function.

For example


<?php
$y = 5; // PHP variable define globally
function quickTest() {

//if you try to use this  PHP variable inside this function,there will be an error

echo "<p>Y is a variable defined outside function quickTest..See error when we try to echo Y: $y</p>";
}
quickTest();

echo "<p>No error because it is used outside the function: $y</p>";
?>

Local variable are the ones that are defined within a function and can only be accessed in that function.This is called local scope.For example


<?php
function quickTest() {
$y = 5; //variable with  local scope
echo "<p>Variable Y is defined within function is: $y</p>";
}
quickTest();

// accessing y outside function will produce error
echo "<p>Y variable is defined outside function: $y</p>";
?>

If we want  to access a global variable within a function,you need to  use global keyword

For example


<?php
$y = 15;
$x = 20;

function quickTest() {
global $x, $y;
$y = $x + $y;
}

quickTest();
echo $y; //This program will  outputs 35 after computing the addition and storing the values.
?>

Global variable  are also stored by PHP in an array called $GLOBAL[index].

Index is the name of the variable.This global array can be accessed in a function and updates  can be done on the global variable directly

For example


<?php
$x = 14;
$y = 11;

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

quickTest();
echo $y; //This code will  outputs 25
?>

 

Static Keyword

Normally once a function has completed the execution,all the local variables are deleted.If we need to retain local variables after a function has executed,we need to use static keyword.Static keyword is used when declaring the variable.


<?php
function quickTest() {
static $y = 0;
echo $y;
$y++;
}

quickTest();
quickTest();
quickTest();
?>

Y will be incremented each time the function is called.
See Next Lesson Here

PHP echo and print

About the Author: Eric K

My name is Eric.Am a software developer with skills in Php,Mysql, Java , Android,Node.js Above all, I have certification in Cisco Networking Associate (CCNA) and holds degree in Information Technology. Hire me: Email : kawi3462@gmail.com