PHP Variable Scopes

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has four different variable scopes:

  • local
  • global
  • static
  • parameter

Local Scope

example:

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

function my()
{
echo $x; // local scope
}

my();
?>

Global Scope

<?php
$x=5; // global scope
$y=10; // global scope

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

my();
echo $c; // outputs 15
?>

Static Scope

When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted.

<?php

function my()
{
static $a=0;
echo $a;
$a++;
}

my();
my();
my();

?>

Parameter Scope

A parameter is a local variable whose value is passed to the function by the calling code.

Example

<?php

function myTest($x)
{
echo $x;
}

myTest(5);

?>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s