Home » Programming » PHP » PHP Scopes in Functions, Loops, Modules, With Examples

PHP Scopes in Functions, Loops, Modules, With Examples

This article explains what variable scopes are, and how they work in the PHP programming language, with code examples.

When programming in any language, you must be aware of how variables are scoped – otherwise, you risk unexpected behaviour, including incorrect calculations, or loss of data – detrimental outcomes for any application (especially if you are working with business records or financial data) that will result in angry users.

What is a Variable?

In computer programming, a variable stores a value, giving it a name that can be used to access it. Once a variable has been created and a value has been assigned to it, the value can be retrieved using the name given to the variable.

The value of a variable can be updated (unless the variable has been declared as a constant), and the variable can be deleted, destroying the value it stores.

Variables can store any kind of value, including numbers, strings, objects, boolean values, and arrays. Some programming languages enforce specific types for variables.

Using variables is one of the core features of object oriented programming – without variables, you would not be able to store values for use elsewhere in your code (unless you were working in a language that let you write directly to memory, which PHP does not).

Declaring Variables in PHP

In PHP, a variable is declared when it is first used.

Declaring a variable in PHP is done as follows:

$myVariable = "Hello LinuxScrew";

Above, a variable named $myVariable is declared using the = (equals) operator, and assigned the string value Hello LinuxScrew.

There are several rules when naming variables in PHP:

  • Variables must all start wit ha $ (dollar sign symbol)
  • Variable names can only contain alphanumeric characters (A-Z, 0-9), and underscores
  • Variables cannot be named $this – this is a special variable that has specific uses

Variables can also be declared without a value:

$myVariable;

What Are Variable Scopes?

Every declared variable has a scope. The scope defines where the variable can be accessed from within your code, and it’s lifetime.

The location (or context) where you declare your variable will determine the scope.

For example, a variable declared inside a function is available only within that function. It cannot be accessed from outside of the function, and the data it stores will be destroyed when the function finishes executing.

Different programming languages follow different scoping conventions, those in PHP are explained below.

PHP Scope Rules

PHP variables usually only have a single scope – one of:

  • Global
  • Local
  • Static

Global Variables

Any variables that are declared outside of a function have a global scope.

<?php

$myVariable = 1;

Above, a global variable called $myVariable is declared and assigned the value 1. It is declared at the root of the PHP code, not within a function, so it is a global variable.

By default global variables are not accessible from within functions – but they can be accesses by using the global keyword:

<?php

$myVariable = 1;
$myOtherVariable = 2;

function multiplyNumbers() {
    global $myVariable, $myOtherVariable;
    return $myVariable * $myOtherVariable;
} 

Above, two global variables are defined. The global keyword is used within the function to declare them for use within the function.

As shown in the example, multiple variables can be declared global by separating them with commas.

You can also access global variables through your code, from within any scope, using the $GLOBALS array:

<?php

$myVariable = "hello there!";

function myFunction() {
    print_r($GLOBALS['myVariable']);
}

Above, a global variable is declared as $myVariable, and then accessed from within a function using the $GLOBALS array that contains a reference to all global variables by name.

The Global Scope and Included PHP Files

The global scope spans all included PHP files.

The following file, data.php defines a variable:

<?php

$myIncludedVariable = 1;

echo $myVariable;

…and when this file is included in a subsequent PHP file:

<?php

$myVariable = 1;
include 'data.php';

echo $myIncludedVariable;

The global scope is shared – the variables from each script are available in the other.

Local Variables

Locally scoped variables are accessible only within the function in which they are declared:

<?php

function myFunction()
{ 
    $myVariable = 1;
} 

Above, the variable $myVariable is only accessible from within the function – attempts to access it from outside of the function will fail.

The default behaviour in PHP is for local variables to be destroyed when the function has completed execution.

Static Variables

As local variables are destroyed when the function ends, you may find yourself declaring global variables for storing values between multiple calls to a function.

It is possible to set a variable to not be destroyed when the function ends using the static keyword. This keeps your code tidy and lets you avoid cluttering up your code with extra variables.

Below, a static variable is declared within a function:

<?php

function countUp() {
    static $counter = 1;
    echo $counter;
    $counter++;
}

countUp(); // Outputs 1
countUp(); // Outputs 2
countUp();  // Outputs 3

The function above declares a static variable counter, that survives when the function has completed executing – retaining its value for the next time the function is run. The function is called multiple times, incrementing the value of the static variable.

If the static keyword were omitted, the value of $counter would be lost after each time the function has completed, and 1 would be output every time.

PHP Variables and Loops, If Statements and Other Code Blocks

Unlike other programming languages like JavaScript, Java, and C++, in PHP variables that are declared inside code blocks are not locally scoped within that block.

Below, two variables are declared as part of a for loop:

  • $i is declared as the loop iterator, and is used to control the state of the loop
  • $myVariable is declared within the loop code blockfor($i=0; $i < 3; $i++) { $myVariable = “hello”; }echo $myVariable; echo $i;

Note that both the variables declared as part of the loop and the variables declared within the loop are in the global scope, accessible from outside of the loop.

This is also the case for other code blocks, like if statements.

When switching between PHP and other programming languages it is vital that you remember how your variables will be scoped. You do not want to use a variable inside a loop, and accidentally change its value in the global scope.

Avoiding Conflict – Name your Variables Sensibly!

This is a problem particularly when re-using variable names in subsequent loops. Once a loop has completed, a following loop may pick up the value of its iterator or a value within it. If you are re-using variable names, be sure to unset their value at the end of the loop, or use sensible, discrete names for your loops.

<?php

for($i=0; $i < 3; $i++) {
    $myVariable = "hello";
}
unset($myvariable);
for($i=0; $i < 3; $i++) {
    echo $myVariable;
}

Above, a variable is destroyed using the unset() function so that it cannot be used further.

If you are including other PHP files, you should also be aware of the global variable names you are using in other files, to avoid another sources of conflict.

Test Your Code

Scope confusion happens to the best of us, regardless of the programming language in use. It’s a common cause of unexpected behaviour or results of calculations, especially when looping through rows of data.

All code has bugs, but the best way to mitigate them is to keep your code as simple as possible, keep it DRY, and testing your code at every step.

Unit testing allows you to set automated tests to confirm that your code is returning the expected value when known data is used and is vital for ensuring the accuracy of your calculations. Additionally, good-old-fashioned manual testing is also a key procedure – users do unexpected things, and you need to be ready to handle that.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment