PHP Anonymous Functions with Example Programs

What are PHP anonymous functions?

PHP anonymous functions are also called closure or lambda functions.

This allows programmers to create and use functions even that are not specified in the language.

The “anonymous” functions were useful for callable parameters and many other uses.

To implement them, you can apply the closure class to your program.

Let us familiarize the correct syntax of anonymous functions and try to implement them in the examples below.

PHP anonymous functions – Syntax

$var=function ($arg1, $arg2) { return $val; };

Here are the attributes of a PHP anonymous function:

  • There is no function name present between the function keyword and the opening parentheses.
  • Its function definition is followed by a semicolon since anonymous function definitions are expressions.
  • The assigned variable is a function, which is then called using the variable’s name.
  • It is known as a callback when supplied to another function that can then call it later.
  • It gets it back from a function outside of it so that it can use the variables of the function outside of it. 

Anonymous Function Example Program

Now let us have our first example using the PHP anonymous function.

However, please bear in mind that the word anonymous function is not known in the PHP language.

Example Program:

<?php
echo preg_replace_callback('~-([a-z])~', function ($abc) {
    return strtoupper($abc[1]);
}, 'Welcome to ITSourceCode!');
?>

Output:

Welcome to ITSourceCode!

Code Explanation:

In this example, we directly use the “anonymous function” without assigning any name for that particular function.

Basically, the implementation of a function is based on the assigned operation within that function.

Therefore, this first example shows you how to use the PHP anonymous function without assigning a specific name to that function.

However, you may assign a name that you desire to specify the function that you want at your convenience.

Example Program for Passing an Anonymous Function to Another Function

Let us have another example where we can pass the PHP anonymous function to another.

This concept will help us use the operation assigned to a specific function and pass this operation to another function.

Example Program:

<?php 
function times_two($a)
{
	return $a * 2;
}

$sample = array(10, 20, 30);
print_r(array_map('times_two', $sample));

?>

Output:

Array ( [0] => 20 [1] => 40 [2] => 60 )

Code Explanation:

As seen in this example, we assign an operation in the function times_two which is to use the variable $a and return $a * 2. The $a * 2 is the assigned operation in the function times_two.

The operation of the function is then passed into another function applied to the next argument. To enable this situation, we call the times_two function as a string to pass the operation in the next argument.

As a result, the program displays the output of Array ( [0] => 20 [1] => 40 [2] => 60 ).

This indicates that the operation of the function works in another argument.

Example Program to Return an Anonymous Function from a Function

From passing the function to another, let us now test to return the PHP anonymous function from a function.

Take a look at the example below.

Example Program:

<?php

function multiply($a)
{
	return function ($b) use ($a) {
		return $a * $b;
	};
}

$double = multiply(2);
echo "The doubled value of 10 is " . $double(10) . ". <br/>";

$tripple = multiply(3);
echo "The trippled value of 10 is " .$tripple(10) . ".";
?>

Output:

The doubled value of 10 is 20.
The trippled value of 10 is 30.

Code Explanation:

In this example, you will see that we have a complex situation in which we try to return another function from another.

So we use the function multiply ($a) to execute its operation to return the function $b using the element $a.

Now to execute the program, we have the two arguments applying the function multiply().

In the first argument, the value of $a is 2, and $b is 10.

This means that we multiply the a and b to come up with our desired output.

This operation also goes the same in the second argument.

Therefore the PHP anonymous function works efficiently in returning the operation from another element.

Scope of the Anonymous Function

In this section, you will be able to understand the scope of an anonymous function in PHP.

See this example to have a clear implementation:

Program Example:

<?php

$message = 'Welcome to ITSourceCode.';
$say = function () use ($message) {
	$message = 'Good day!';
	echo $message . "<br/>";
};

$say();
echo $message;
?>

Output:

Good day!
Welcome to ITSourceCode.

Code Explanation:

The example signifies that the scope of the PHP anonymous function includes constants, properties, and methods.

This means that the anonymous function supports a lot of operations within its scope with the proper declaration.

Summary

In summary, the topic has now covered all the information you need to fully understand the PHP anonymous function.

The topic also stresses diverse uses of the function which opens a lot of opportunities for programmers.

Through the PHP anonymous function, programmers are allowed to define the function with their desired operations. It also improves programmers’ experience and their exploration of new skills.

Common use cases for PHP Anonymous Functions

  • Input validation. Check that expected data is present before using it in business logic.
  • Conditional rendering. Display forms differently for logged-in vs guest users.
  • Guard clauses. Early return at the top of a function if required data is missing.
  • Session and cookie checks. Verify a user’s authentication state before serving protected content.
  • Configuration existence. Confirm a config value is set before falling back to a default.

Working code example

<?php
function greet($name = null) {
    if (!isset($name) || $name === "") {
        return "Hello, guest!";
    }
    return "Hello, " . htmlspecialchars($name) . "!";
}

echo greet("Alice"); // Hello, Alice!
echo greet();        // Hello, guest!
echo greet("");      // Hello, guest!
?>

Common pitfalls

  • isset() vs empty(). isset() checks if variable exists and is not null. empty() also returns true for 0, “”, “0”, empty arrays.
  • Undefined index warnings. Accessing $_POST[“key”] without isset() first triggers E_WARNING in PHP 7 and E_DEPRECATED in PHP 8.
  • Falsey values. null, false, 0, “”, “0”, empty array all evaluate to false. Use === for strict comparison when needed.
  • Function name conflicts. If your function name matches a PHP built-in, PHP throws a fatal error. Prefix with your namespace.

Best practices

  • Use type declarations. function greet(?string $name = null): string catches wrong types at compile time.
  • Early return over deep nesting. Guard clauses at the top improve readability.
  • Prefer null-safe operator (PHP 8+). $user?->getName() cleaner than isset() chains.
  • Namespace your functions. Group related functions in a namespace to avoid pollution.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Mary Grace G. Patulada


Programmer & Technical Writer at PIES IT Solution

Mary Grace G. Patulada (pen name ‘Nym’) is a programmer and writer at PIES IT Solution with a BSIT background from Carlos Hilado Memorial State College, Binalbagan Campus. Authored 370+ UML diagram tutorials and capstone documentation guides at itsourcecode.com. Specializes in UML (class, use case, activity, sequence, component, deployment), DFD, and ER diagrams for BSIT capstone projects.

Expertise: UML Diagrams · DFD · ER Diagrams · Use Case Diagrams · Activity Diagrams · Capstone Documentation · PHP
 · View all posts by Mary Grace G. Patulada →

Leave a Comment