PHP Functions: User-Defined Functions, Parameters, Return Types & Closures

In procedural and functional programming, writing monolithic scripts where the same calculations repeat dozens of times leads to messy, fragile code. A function is a reusable, modular block of code that executes only when called. PHP includes over 1,000 built-in functions, and allows you to create customized User-Defined Functions with strict parameter types, default values, variadic argument lists, and modern PHP 8 arrow functions.

Creating & Invoking a User-Defined Function

A function declaration begins with the function keyword, followed by an identifier name and a parameter list enclosed in parentheses:

<?php
    // Declaring the function
    function displayUniversityWelcome() {
        echo "<h3>Welcome to the BCA Computer Science Portal - Veewom</h3>";
    }

    // Invoking (calling) the function
    displayUniversityWelcome();
?>

Function Parameters & Default Argument Values

Functions accept input data via parameters. You can specify default fallback values that apply whenever the caller omits an argument:

<?php
    // $role has a default argument value of "Student"
    function greetUser(string $name, string $role = "Student") {
        echo "Hello, " . $name . "! Your portal role is: " . $role . ".<br>";
    }

    greetUser("Aakash");                // Uses default role: Student
    greetUser("Dr. Sharma", "Professor"); // Overrides default role: Professor
?>

Pass by Value vs Pass by Reference (&)

Understanding how data passes into a function is a standard semester examination topic:

Mechanism Syntax Effect on Original Variable
Pass by Value (Default) function addTen($num) A local copy is created. Original variable outside remains untouched.
Pass by Reference function addTen(&$num) Direct memory pointer passed. Modifying $num directly changes the original variable outside!
<?php
    $score = 50;

    function addGraceMarksByReference(&$marks) {
        $marks += 5; // Directly modifies memory address
    }

    addGraceMarksByReference($score);
    echo "Updated Score: " . $score; // Outputs: 55 (Original modified!)
?>

Variable-Length Arguments: Variadic Splat Operator (...)

If you do not know how many arguments the caller will provide, use the splat operator (...) to collect all arguments into an array:

<?php
    function calculateGrandTotal(int ...$numbers): int {
        return array_sum($numbers);
    }

    echo calculateGrandTotal(10, 20, 30) . "<br>";       // Outputs: 60
    echo calculateGrandTotal(5, 15, 25, 35, 45);         // Outputs: 125
?>

Modern PHP 8 Return Type Declarations

Explicitly specifying the expected return data type makes your code self-documenting and catches runtime errors early:

<?php
    // Colon followed by type: function name(): returnType
    function calculateSimpleInterest(float $principal, float $rate, int $timeYears): float {
        $interest = ($principal * $rate * $timeYears) / 100;
        return $interest;
    }

    // Returning nullable types (?string means string or null)
    function findUserByEmail(string $email): ?string {
        if ($email === "admin@veewom.com") {
            return "Super Administrator";
        }
        return null; // Valid because of ? prefix
    }
?>

Arrow Functions (Closures) in PHP

For short callback routines (e.g. array mapping or filtering), arrow functions provide clean, concise syntax that automatically inherits variables from the outer scope:

<?php
    $multiplier = 3;
    $numbers = [1, 2, 3, 4, 5];

    // fn(arguments) => expression;
    $tripled = array_map(fn($n) => $n * $multiplier, $numbers);

    // Outputs: [3, 6, 9, 12, 15]
    print_r($tripled);
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: What is a recursive function? Give an example.
A: A recursive function is a function that calls itself until it reaches a defined base termination condition. A classic example is calculating the Factorial of a number:
function fact($n) { return ($n <= 1) ? 1 : $n * fact($n - 1); }.

Interactive Student Practice Session

Exercise 11.1: Write a recursive PHP function to generate the Fibonacci series up to N terms.

Exercise 11.2: Write a function formatCurrency(float $amount, string $currency = "INR"): string with strict return typing that outputs formatted strings like "INR 4,500.00".

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!