Broad Network


Basics of Variable Scope in PHP

Variable Scope in PHP - Part 1

Foreword: In this part of the series, I give you the basics of PHP variable scope.

By: Chrysanthus Date Published: 17 Nov 2018

Introduction

This is part 1 of my series, Variable Scope in PHP. In this part of the series, I give you the basics of PHP variable scope. A block is a set of statements enclosed in curly braces, which are { and }. The question here is: if a variable is declared outside a block, will it be seen in the block? On the other hand, if it is declared inside the block, will it be seen outside the block? Blocks do not occur arbitrarily in code. There are certain constructs that have blocks.  The following constructs have blocks: if, for, try, and catch. You should have seen these structures (statements) before.

For the rest of this tutorial, we look at the if, for and try/catch control structures and how variable scope is applied to them. Some code samples below, may not work; do not worry about that.

You should have read the previous series before reaching here, as this is the continuation.

The if Structure and Variable Scope
Test the following code:

    <?php

        $hisVar = "his stuff";

        if (25 == 25)
            {
                    echo ($hisVar);
                $herVar = "her stuff";
            }

        //echo($herVar);

    ?>

The if condition is, if 25 equals 25. Now this condition will always return true, and so the if block will always be executed. Outside the if-block, the variable, $hisVar is declared and assigned the value, "his stuff". Inside the if-block there is a statement to print $hisVar at the web page. This variable was declared outside the block; if it should be seen inside the block, it will be printed (displayed). If you tried the code you would have noticed that the value of $hisVar was printed (seen inside the block).

Now, inside the block, a new variable, $herVar is declared and has a value assigned to it. Outside the block, there is a comment. This comment is actually a statement preceded by the comment denotation, //. Because of this preceding sign, the statement is not executed. If you remove the comment and re-test the code, the following explanation will follow:

The $herVar variable is declared inside the block. Now, if it should be seen outside the block, then the last statement (with the comment denotation, removed) would print its value. Remove the // symbol and try the code and note that the last write statement would work, and you would see “her stuff” printed (on the same line in the web page).

So, a variable declared outside the if-block is seen inside the if-block; a variable declared inside the if-block is also seen outside the if-block. Also note that a variable declared outside the if-block is also seen in the if-condition (parentheses).

The for Construct and Variable Scope
The following code has been written similar to the above; the variables and print (echo) statements have been written in a similar way.

Test the code:

    <?php

        $hisVar = "his stuff";

        for ($i=0; $i< 3; ++$i)
            {
                echo ($hisVar);
                $herVar = "her stuff";
            }

        //echo($herVar);
        //echo($i);

    ?>

You should have tried the code. Note that the variable declared outside the for-block is seen inside the for-block. In this case the value of the variable is printed 3 times (on the same line).

Now remove the comment denotation in the last-but-one line and try the code again; the value of the variable, $herVar, is printed (still on the same line). This is because a variable declared inside the for-block is seen outside the for-block (and vice-versa).

Remove the comment symbol from the very last line of the above script code. If the variable, that has been declared in the for-loop parentheses, can be seen outside the for-structure (loop), then the last statement (line) will display it. Test the code (with the last comment symbol removed) and note that the variable is seen outside the for-structure.

Now, a variable declared outside the for-block is seen inside the for-block; a variable declared inside the for-block is seen outside the for-block, as demonstrated above. A variable declared outside the for-structure is seen inside the for-loop parentheses; a variable declared inside the for-loop parentheses is seen outside the for-structure (the value of 3 is printed above).
This remark is applicable to while-loops as well.

The Try/Catch Structure

Read through the following code:

    <?php

        $input = 0;

        $err = new Exception("Division by zero is not allowed!");   //wrong position

        try
            {
                if ($input == 0)
                    throw $err;
                $answer = 8 / $input;
                echo $answer;
            }
        catch (Exception $err)
            {
                echo $err->getMessage(), '<br>';
                echo $err->getFile(), '<br>';
                echo $err->getLine(), '<br>';

                $seen = 'seen';
                echo $seen;
            }  

    ?>

Test the code.

The above remarks are also applicable to the try/catch structure. In my computer, the output is:

    Division by zero is not allowed!
    C:Apache24htdocstemp.php
    5
    seen

Included File
Type the following code and save the file with the name, temp.php :

<?php

    echo $ofInclude, '<br>';

    $ofMain1 = 1;
    include ("temp2.php");
    echo $ofInclude, '<br>';
    $ofMain2 = 2;

    echo $ofMain1, '<br>';
    echo $ofMain2, '<br>';

?>

Type the following code and save it with the name temp2.php in the same directory as the above file:

<?php

    echo $ofMain1, '<br>';

    $ofInclude = 'A';

?>

Run the temp.php script.

Note the position of the include statement, in the main script. The variable, $ofMain1 is available (seen) in the included file. However, $ofMain2 is not available (seen) there.

When a file is included inside a main script, all the global variables of the file are available in the main script, from the point of inclusion, downward.

The output is:

    NULL
    1
    A
    1
    2

That is it for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

NEXT

Comments