Web Development /PHP Programming / Lesson
Web Development

Functions

Learn how to create reusable PHP functions, work with parameters and return values, control variable scope, use default and variadic arguments, create closures and arrow functions, pass callbacks, and apply recursion and function best practices.

🎯

Learning Objectives

["Explain what a function is and why functions are important in PHP programming.","Declare and call user-defined PHP functions using the function keyword.","Differentiate between parameters and arguments.","Use return values to send results from functions back to the calling code.","Use default parameters, type declarations, nullable types, void, mixed, and union types appropriately.","Understand the difference between passing arguments by value and by reference.","Create variadic functions using the spread operator syntax.","Use named arguments, local variables, global variables, and static variables correctly.","Create anonymous functions, closures, arrow functions, and callback functions.","Understand recursion and apply function design, naming, documentation, and reusability best practices."]

📖

Lesson Content

Introduction to PHP Functions

A function is a reusable block of PHP code designed to perform a specific task. Instead of writing the same instructions repeatedly, you can place them inside a function and call that function whenever the task is needed.

Functions are one of the most important concepts in programming because they make applications easier to organize, reuse, test, debug, and maintain.

For example, if an application needs to calculate a student’s average several times, it is better to create one function for the calculation than to repeat the calculation logic throughout the application.

Why Functions Matter

  • They reduce code duplication.
  • They make programs easier to read.
  • They divide large programs into smaller tasks.
  • They make code easier to test and debug.
  • They encourage code reuse.
  • They help developers build maintainable applications.

1. Creating a Function

A user-defined PHP function is declared using the function keyword.

<?php

function greet() {
    echo "Welcome to Dwallnet Technologies!";
}

?>

The function above is named greet. Declaring a function does not automatically execute it.

2. Calling a Function

To execute a function, call its name followed by parentheses.

<?php

function greet() {
    echo "Welcome to Dwallnet Technologies!";
}

greet();

?>

When greet() is executed, the code inside the function runs.

3. Function Parameters and Arguments

A parameter is a variable defined in a function declaration. An argument is the actual value supplied when the function is called.

<?php

function greetStudent($name) {
    echo "Welcome, " . $name;
}

greetStudent("Daniel");

?>

In this example, $name is the parameter and "Daniel" is the argument.

4. Multiple Parameters

A function can accept multiple parameters.

<?php

function addNumbers($first, $second) {
    return $first + $second;
}

$result = addNumbers(10, 20);

echo $result;

?>

The arguments are matched to parameters according to their position unless named arguments are used.

5. Return Values

The return statement sends a value from a function back to the code that called it.

<?php

function calculateArea($length, $width) {
    return $length * $width;
}

$area = calculateArea(10, 5);

echo $area;

?>

A returned value can be stored in a variable, displayed, compared, passed to another function, or used in another expression.

6. Return Versus Echo

echo displays information immediately, while return sends a value back to the caller.

<?php

function getName() {
    return "Ada";
}

$name = getName();

echo $name;

?>

Returning values generally makes functions more reusable because the calling code decides what to do with the result.

7. Default Parameters

A function parameter can have a default value. The default value is used when the caller does not provide an argument for that parameter.

<?php

function greetUser($name = "Student") {
    return "Hello, " . $name;
}

echo greetUser();
echo greetUser("Michael");

?>

When a function has both required and optional parameters, required parameters should normally come before optional parameters.

8. Type Declarations

Modern PHP allows developers to declare the expected types of function parameters and return values.

<?php

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(10, 20);

?>

Common parameter and return types include:

  • int
  • float
  • string
  • bool
  • array
  • object
  • mixed
  • void

9. Nullable Types

A nullable type allows a value to contain either the specified type or null.

<?php

function findUserName(?string $name): ?string {
    return $name;
}

echo findUserName(null);

?>

The question mark before a type indicates that null is also accepted.

10. Void Functions

A function that does not return a value can use the void return type.

<?php

function showMessage(string $message): void {
    echo $message;
}

showMessage("Hello PHP!");

?>

11. Mixed Type

The mixed type indicates that a function can accept or return values of different PHP types.

<?php

function displayValue(mixed $value): void {
    var_dump($value);
}

displayValue("PHP");
displayValue(100);
displayValue(true);

?>

Although mixed is useful in some situations, specific types should normally be preferred when the expected data is known.

12. Union Types

Modern PHP supports union types, allowing a parameter or return value to accept more than one specified type.

<?php

function formatId(int|string $id): string {
    return "ID: " . $id;
}

echo formatId(25);
echo formatId("STUDENT-25");

?>

13. Passing Arguments by Value

By default, PHP passes function arguments by value. The function receives a value that it can work with without directly changing the caller’s variable.

<?php

function increase($number) {
    $number++;
}

$value = 10;

increase($value);

echo $value;

?>

The original $value remains unchanged in this example.

14. Passing Arguments by Reference

PHP can pass a variable by reference by placing & before the parameter name.

<?php

function increaseValue(&$number) {
    $number++;
}

$value = 10;

increaseValue($value);

echo $value;

?>

Because the parameter is passed by reference, the function can modify the original variable.

References should be used intentionally. In many situations, returning a new value is clearer and easier to maintain.

15. Variadic Functions

A variadic function can accept an unknown number of arguments by using ... before a parameter.

<?php

function calculateTotal(...$numbers) {
    return array_sum($numbers);
}

echo calculateTotal(10, 20, 30, 40);

?>

Inside the function, $numbers is available as an array.

16. Named Arguments

Modern PHP allows arguments to be passed by parameter name.

<?php

function createStudent($name, $course, $level) {
    return "$name - $course - Level $level";
}

echo createStudent(
    name: "Grace",
    course: "Web Development",
    level: 200
);

?>

Named arguments can make calls clearer, especially when a function has several parameters.

17. Variable Scope

Variable scope determines where a variable can be accessed.

A variable created inside a function is normally local to that function.

<?php

function testScope() {
    $message = "Inside function";

    echo $message;
}

testScope();

?>

The local variable $message is not automatically available outside the function.

18. The Global Keyword

A variable defined outside a function belongs to the global scope. The global keyword can make a global variable available inside a function.

<?php

$siteName = "Dwallnet Technologies";

function showSiteName() {
    global $siteName;

    echo $siteName;
}

showSiteName();

?>

Although global is available, excessive use of global variables can make applications harder to understand and test. Passing required data as parameters is usually clearer.

19. Static Variables

A local variable normally disappears when a function finishes. A variable declared with static keeps its value between function calls.

<?php

function visitCounter() {
    static $count = 0;

    $count++;

    return $count;
}

echo visitCounter();
echo visitCounter();
echo visitCounter();

?>

The function remembers the value of $count between calls.

20. Anonymous Functions

An anonymous function is a function without a traditional function name. It can be stored in a variable or passed to another function.

<?php

$greet = function($name) {
    return "Hello, " . $name;
};

echo $greet("Daniel");

?>

Anonymous functions are commonly used as callbacks.

21. Closures

A closure is an anonymous function that can capture variables from its surrounding scope using the use keyword.

<?php

$prefix = "Student";

$label = function($name) use ($prefix) {
    return $prefix . ": " . $name;
};

echo $label("Grace");

?>

22. Arrow Functions

Arrow functions provide a shorter syntax for simple anonymous functions.

<?php

$numbers = [1, 2, 3, 4, 5];

$squares = array_map(
    fn($number) => $number * $number,
    $numbers
);

print_r($squares);

?>

Arrow functions automatically capture variables from the parent scope by value.

23. Callback Functions

A callback is a function passed to another function so that it can be executed later or used as part of a process.

<?php

function processNumber($number, callable $callback) {
    return $callback($number);
}

$result = processNumber(
    10,
    fn($value) => $value * 2
);

echo $result;

?>

Callbacks are widely used with array functions such as array_map(), array_filter(), and array_reduce().

24. Functions with Arrays

Functions are useful for processing collections of data.

<?php

function calculateAverage(array $scores): float {
    if (count($scores) === 0) {
        return 0;
    }

    return array_sum($scores) / count($scores);
}

$scores = [70, 80, 90, 85];

echo calculateAverage($scores);

?>

25. Validation Functions

Functions can isolate validation rules so they can be reused throughout an application.

<?php

function isValidEmail(string $email): bool {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

if (isValidEmail("student@example.com")) {
    echo "Valid email address.";
}

?>

26. Recursive Functions

Recursion occurs when a function calls itself. A recursive function must have a condition that stops the recursion.

<?php

function countdown(int $number): void {
    if ($number <= 0) {
        echo "Done!";
        return;
    }

    echo $number . "<br>";

    countdown($number - 1);
}

countdown(5);

?>

Without a proper stopping condition, recursion can continue unnecessarily and cause problems. Recursive solutions should therefore be designed with a clear base case.

27. Recursive Factorial Example

<?php

function factorial(int $number): int {
    if ($number <= 1) {
        return 1;
    }

    return $number * factorial($number - 1);
}

echo factorial(5);

?>

The function repeatedly calls itself until it reaches the base case.

28. Built-in Functions and User-defined Functions

PHP provides thousands of built-in functions for common programming tasks.

<?php

echo strlen("Dwallnet");
echo strtoupper("php");

$numbers = [10, 20, 30];

echo array_sum($numbers);

?>

Developers can also create their own user-defined functions for application-specific tasks.

29. Function Naming

Function names should clearly describe what the function does.

Prefer names such as:

calculateTotal()
validateEmail()
getStudentName()
createInvoice()
sendNotification()

Avoid vague names such as:

doThing()
process()
test1()
abc()

Clear names make code easier for other developers to understand.

30. Keep Functions Focused

A good function should normally perform one clearly defined task.

Instead of creating one huge function that validates a student, saves a database record, sends an email, and generates a report, those responsibilities can be separated into smaller functions.

<?php

function validateStudent($student) {
    // Validation logic.
}

function saveStudent($student) {
    // Database logic.
}

function sendWelcomeEmail($student) {
    // Email logic.
}

?>

Small focused functions are easier to test and reuse.

31. Function Documentation

PHPDoc comments can describe what a function does, the parameters it accepts, and what it returns.

<?php

/**
 * Calculates the total price of a list of products.
 *
 * @param float[] $prices Product prices.
 * @return float Total price.
 */
function calculateTotal(array $prices): float {
    return array_sum($prices);
}

?>

Documentation is particularly useful in larger projects and team environments.

32. Practical Example: Student Result

<?php

function calculateAverage(array $scores): float {
    if (count($scores) === 0) {
        return 0;
    }

    return array_sum($scores) / count($scores);
}

function getGrade(float $average): string {
    if ($average >= 70) {
        return "A";
    }

    if ($average >= 60) {
        return "B";
    }

    if ($average >= 50) {
        return "C";
    }

    if ($average >= 40) {
        return "D";
    }

    return "F";
}

$scores = [75, 68, 82, 70];

$average = calculateAverage($scores);
$grade = getGrade($average);

echo "Average: " . $average . "<br>";
echo "Grade: " . $grade;

?>

This example demonstrates how multiple small functions can work together to solve a larger task.

33. Practical Example: Reusable Calculator

<?php

function calculate(float $first, float $second, string $operator): float {
    return match ($operator) {
        '+' => $first + $second,
        '-' => $first - $second,
        '*' => $first * $second,
        '/' => $second != 0 ? $first / $second : 0,
        default => 0
    };
}

echo calculate(20, 5, '+');
echo calculate(20, 5, '*');

?>

Functions allow the calculation logic to be reused with different values.

34. Functions and Maintainability

When a rule exists in only one function, changing that rule later becomes easier.

For example, if a website calculates membership discounts, placing the discount calculation in one function allows the business rule to be updated in one location instead of many different pages.

35. Best Practices for PHP Functions

  • Give functions descriptive names.
  • Keep functions focused on a specific responsibility.
  • Use parameters instead of unnecessary global variables.
  • Return values when the calling code needs to decide what to do with the result.
  • Use type declarations when they improve clarity and reliability.
  • Use default parameters for sensible optional values.
  • Use variadic parameters when a function genuinely needs a variable number of arguments.
  • Use callbacks and closures when they make reusable operations clearer.
  • Always provide a safe stopping condition for recursive functions.
  • Document important or complex functions.
  • Avoid unnecessarily long functions.
  • Avoid hidden dependencies on global state.

36. Functions in Real PHP Applications

Functions are used throughout real PHP applications, including WordPress plugins and themes, APIs, dashboards, authentication systems, payment systems, content management systems, and database-driven applications.

For example, a WordPress plugin may contain separate functions for registering settings, processing forms, querying the database, validating user input, rendering administrative pages, and handling AJAX requests.

Lesson Summary

Functions allow PHP developers to organize programs into reusable units of logic. A function can receive parameters, perform an operation, and return a result.

Modern PHP provides powerful function features including type declarations, nullable and union types, default parameters, references, variadic parameters, named arguments, closures, arrow functions, callbacks, and recursion.

Well-designed functions make applications easier to read, maintain, test, debug, and expand.

💻

Code Example

<?php

/**
 * Calculates a student's average score.
 *
 * @param int[] $scores Student scores.
 * @return float Average score.
 */
function calculateAverage(array $scores): float {
    if (count($scores) === 0) {
        return 0;
    }

    return array_sum($scores) / count($scores);
}

/**
 * Converts an average score into a grade.
 */
function getGrade(float $average): string {
    if ($average >= 70) {
        return 'A';
    }

    if ($average >= 60) {
        return 'B';
    }

    if ($average >= 50) {
        return 'C';
    }

    if ($average >= 40) {
        return 'D';
    }

    return 'F';
}

$scores = [75, 68, 82, 70];

$average = calculateAverage($scores);
$grade = getGrade($average);

echo "Average: " . $average . PHP_EOL;
echo "Grade: " . $grade . PHP_EOL;

/*
 * Variadic function example.
 */
function calculateTotal(float ...$numbers): float {
    return array_sum($numbers);
}

echo calculateTotal(10, 20, 30) . PHP_EOL;

/*
 * Callback example.
 */
function processValue(int $value, callable $callback): int {
    return $callback($value);
}

$result = processValue(
    10,
    fn(int $number): int => $number * 2
);

echo $result . PHP_EOL;
⭐

Key Takeaways

["A PHP function is a reusable block of code designed to perform a specific task.","Functions are declared with the function keyword and must be called before their code executes.","Parameters receive values while arguments are the values supplied when a function is called.","The return statement sends a result back to the calling code.","Default parameters provide fallback values for optional arguments.","Type declarations improve clarity by describing expected parameter and return types.","PHP supports passing arguments by value and by reference.","Variadic parameters allow a function to receive a variable number of arguments.","Local, global, and static variables have different scopes and lifetimes.","Anonymous functions, closures, arrow functions, and callbacks support flexible and reusable programming patterns.","Recursive functions must have a clear stopping condition.","Small, focused, well-named functions improve application readability and maintainability."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress