PHP: Scope

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Scope

Aims:

Common error I: invoking an undefined function

function output_paragraph( $text )
{
    echo "<p>{$text}</p>";
}

outputParagraph( 'Today is ' . Date('d/m/y') );

Common error II

A novice programmer incorrectly thinks that the radius (5) is available inside this function

function get_circle_area()
{
    return 3.14 * $radius * $radius;
}

$radius = 5;
$area = get_circle_area();
echo "<p>The area of the circle is {$area}</p>";

Common error III

A novice programmer incorrectly thinks that the circumference (31.4) is available outside of this function

function get_circle_circumference( $diameter )
{
    $circumference = 3.14 * $diameter;
}

echo '<p>';
echo 'The circumference is ';
get_circle_circumference( 10 );
echo $circumference;
echo '</p>';

Variables in PHP

Formal parameters and local variables

Global variables and superglobal variables

Class exercise

Draw boxes on this program to show the scope of each variable

$v1 = 10;
$v2 = $v1 / 2;
echo "<p>{$v1} {$v2}</p>";

function f( $x1 )
{
    echo "<p>{$x1}</p>";
    $x2 = 25;
    $x3 = $x2 * $x1;
    echo "<p>{$x2} {$x3}</p>";
}

$v3 =  2;
f(6);
f($v3 + $v2);
echo "<p>{$v3}</p>";

Using a variable outside its scope

Class exercise: what is the output of the following?

function func1()
{
    echo $x;
}    

$x = 10;
func1();

Class exercise: what is the output of the following?

function func2()
{
    $x = $x + 1;
}    

$x = 5;
func2();
echo $x;

Class exercise: what is the output of the following

function larger( $x, $y )
{
    $maximum = $y;
    if ( $x > $y )
    {
        $maximum = $x;
    }
    return $maximum;
} 

echo '<p>';
echo larger( 3, 2 );
echo ' ';
echo $maximum;
echo '</p>';

Class exercise

Pointers for advanced students