3 Functions And Variable Scope

Web Technology II · Unit 3

Functions and Variable Scope

Exam-focused notes for Functions and Variable Scope (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

Functions and Variable Scope in short

Functions let us group code under a name and reuse it. This chapter covers how to define functions, pass values, and control where a variable can be seen.

Functions and Variable Scope: notes

Function definition and invocation

A function is a named block of code that does one job. It is defined once and called many times.

<?php
function greet($name) {
    echo "Hello, $name! ";
}

greet("Ram");     // call
greet("Sita");
  • Use the function keyword, then a name, then brackets.
  • Function names are not case sensitive, but keep one style.
  • A function can be called before it is defined in the file, if it is defined at the top level.
  • Functions help to avoid repeated code and make programs easier to test.

PHP also has built-in functions such as strlen(), count() and date().

Function parameters and return values

Parameters are the inputs in the definition. Arguments are the actual values passed in the call. The return statement sends a result back and ends the function.

<?php
function area(float $length, float $width = 1): float {
    return $length * $width;
}

echo area(5, 4);   // 20
echo area(5);      // 5, default width is used
  • A parameter can have a default value. Parameters with defaults go last.
  • Type hints such as int or string are optional.
  • A function returns one value. To return many values, return an array.
  • PHP 8 allows named arguments: area(width: 3, length: 7).
<?php
function minMax(array $a) {
    return [min($a), max($a)];
}
[$lo, $hi] = minMax([4, 9, 1]);

What this unit covers

  • Function definition and invocation
  • Function parameters and return values
  • Parameters by reference
  • Global variables and scope
  • Static variables and scope
  • Anonymous functions and variable functions
  • Missing parameters handling

Global variables and scope

2081 · 10 marks

How can you define and declare functions? Differentiate global variable from static variable. Write a PHP program to demonstrate the use of global and static variables.[10]

--- A function is a block of reusable code that performs a specific task. In PHP, functions are defined using the function keyword. - Function names are case-insensitive - Function names must start with a letter or underscore - Parameters are optional - The return statement is optional - Function...

Open this answer on its own page →

Parameters by reference

2080 · 10 marks

Describe variables and missing parameters with examples. Write a PHP program to implement functions containing parameters by reference.[10]

--- A variable in PHP is a named storage location that holds a value. PHP variables: - Start with a

Open this answer on its own page →

Anonymous functions and variable functions

2080 · 5 marks

Differentiate anonymous function from variable function. [5]

An anonymous function (also called a closure) is a function that is defined without a name. It can be assigned to a variable, passed as an argument, or returned from another function. Syntax: - The function itself has no identifier/name. - It is defined using the function keyword without a name. ...

Open this answer on its own page →

Static variables and scope

2079 · 10 marks

What are variables? How can you define static variables? Write a PHP program to illustrate the use of Switch statement.[10]

Show solved answer

Variables, Static Variables & Switch Statement in PHP

A. Variables in PHP

A variable is a named container used to store data values that can be used and manipulated throughout a program.

Key Rules for PHP Variables:

  • All variables begin with the $ sign followed by the variable name
  • Variable names must start with a letter or underscore (_)
  • Variable names cannot start with a number
  • Variable names are case-sensitive ($age and $Age are different)
  • PHP is a loosely typed language, so data types do not need to be declared explicitly

Example:

<?php
    $name  = "Alice";   // String variable
    $age   = 20;        // Integer variable
    $price = 49.99;     // Float variable
    echo $name;
    echo $age;
?>

B. Static Variables

A static variable is a local variable that retains its value between function calls instead of being destroyed when the function exits.

Characteristics:

  • Declared using the keyword static before the variable name
  • Initialized only once (on the first function call)
  • On subsequent calls, it remembers its previous value
  • Commonly used for counters and state tracking

Syntax:

static $variable_name = value;

Example:

<?php
    function counter() {
        static $count = 0;   // initialized only once
        $count++;
        echo "Count = $count  ";
    }

    counter();   // Output: Count = 1
    counter();   // Output: Count = 2
    counter();   // Output: Count = 3
?>

Here, $count is not reset to 0 on each call because it is declared as static. Without static, the output would always be Count = 1.


C. PHP Program to Illustrate the Switch Statement

The switch statement evaluates an expression and executes the matching case block. It is a cleaner alternative to multiple if...elseif...else chains.

Syntax:

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // code block
}

Program:

<?php
    $day = 3;

    switch ($day) {
        case 1:
            echo "Monday";
            break;
        case 2:
            echo "Tuesday";
            break;
        case 3:
            echo "Wednesday";
            break;
        case 4:
            echo "Thursday";
            break;
        case 5:
            echo "Friday";
            break;
        case 6:
            echo "Saturday";
            break;
        case 7:
            echo "Sunday";
            break;
        default:
            echo "Invalid day number";
    }
?>

Output:

Wednesday

Key Points about Switch:

FeatureDescription
breakStops execution and exits the switch block
Without breakExecution falls through to the next case
defaultExecutes when no matching case is found
ComparisonUses loose comparison (==) between expression and cases

Summary

ConceptDescription
VariableNamed container starting with $ to store data
Static VariableLocal variable that persists its value across function calls
Switch StatementMulti-branch control structure based on matching case values
Open this answer on its own page →

Function definition and invocation

0 · 10 marks

What is a function? How can you define and call a function in PHP? Write a PHP program to implement a function with parameters and return value.[10]

A function is a reusable block of code that performs a specific task. It can accept input values (called parameters) and can send back a result (called a return value) to the calling code. Key benefits of using functions: - Code reusability - write once, call many times - Modularity - breaks a la...

Open this answer on its own page →