Sling Academy
Home/PHP/How to define and call functions in PHP

How to define and call functions in PHP

Last updated: January 09, 2024

Introduction

Mastering functions in PHP enhances your ability to write reusable and organized code. This tutorial covers the essentials of defining and calling functions in PHP, with progressive examples designed to elevate your coding skills.

What Are Functions in PHP?

Functions in PHP are blocks of code that encapsulate specific tasks, and can be reused throughout your application. They simplify the coding process, prevent repetition, and make the codebase more maintainable.

Defining a Basic Function

function greet() {
    echo "Hello, World!";
}

To call the function you simply use its name followed by parentheses:

greet(); // Output: Hello, World!

Function with Parameters

Parameters allow functions to accept input and make them more versatile:

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

Call this function with an argument like this:

greet('Alice'); // Output: Hello, Alice!

Returning Values from Functions

Returning values from functions is critical when you need to use the result of a function for further processing:

function add($a, $b) {
    return $a + $b;
}
$sum = add(5, 3);
echo $sum; // Output: 8

Function with Default Parameter Values

Default parameter values are used when no arguments or null are passed:

function greet($name = 'Guest') {
    echo "Hello, $name!";
}

You can call it with or without an argument:

greet('Alice'); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!

Type Declarations and Return Types

PHP 7 introduced type declarations and return types to functions. These provide better error handling and code readability:

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

The above function ensures that only numbers are passed and returned.

Anonymous Functions

Anonymous functions, also known as closures, are functions without a name and can be assigned to variables or passed as arguments to other functions:

$greet = function($name) {
    echo "Hello, $name!";
};
$greet('Alice'); // Output: Hello, Alice!

Passing Functions as Parameters

PHP allows passing functions as parameters, enabling advanced callbacks and higher-order functions:

function shout($string, $callback) {
    echo $callback($string);
}
shout('hello', 'strtoupper'); // Output: HELLO

Variable Functions

Variable functions allow you to use a variable to call a function with the same name:

$func = 'greet';
$func('Alice'); // Calls greet('Alice')

Recursive Functions

Recursive functions let you solve complex problems by calling itself with modified parameters:

function factorial($number) {
    if ($number <= 1) {
        return 1;
    } else {
        return $number * factorial($number - 1);
    }
}
echo factorial(5); // Output: 120

Namespaces and Functions

PHP Namespaces allow organizing and grouping functions under a specified namespace. This is particularly useful in avoiding name collisions between code from different libraries.

namespace MathHelpers;
function add($a, $b) {
    return $a + $b;
}

When calling from a different namespace:

echo MathHelpers\add(5, 3); // Output: 8

Conclusion

Your journey through PHP functions is pivotal in writing effective code. By mastering the basics of function declaration, parameters, return types, and advanced concepts like recursion and namespaces, you’re now equipped to tackle a multitude of programming challenges with PHP.

Next Article: How to use callback functions in PHP

Previous Article: Understanding NULL in PHP

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array