Local And Global Variable Scope in PHP

by Hiroshi on June 22, 2008

in PHP Basics, Variable Scope

Variable Scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single or local scope. This single scope spans included and required files as well.

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

Global scope means a variable is available for whole document or site all the time.

Local Scope means a variable is available within limits in a function or an area.

Global Variables: $GLOBALS

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don’t need to do a global $GLOBALS; to access it within functions or methods.

You may specify a PHP array containing “global variables”.

<?php
$global_vars = array(); // This array must be associative
?>

For instance, let’s say you want to define a weblog name and a Template Group name. You could use this:

<?php
$global_vars = array("my_weblog_name" => "news","my_template_group" => "display");
// Last entry must not include the comma at the end
?>

Related Posts

Previous post:

Next post: