0
0
PHPprogramming~5 mins

Anonymous function syntax in PHP

Choose your learning style9 modes available
Introduction

Anonymous functions let you create small pieces of code without giving them a name. They are useful when you want to use a function just once or pass it around easily.

When you want to quickly create a function to use as a callback.
When you need a small function inside another function without naming it.
When you want to pass a function as an argument to another function.
When you want to keep your code clean by not cluttering it with many named functions.
Syntax
PHP
<?php
$variable = function($parameters) {
    // code here
};

The function is assigned to a variable, so you can call it using that variable.

Anonymous functions can also use variables from outside their scope using the use keyword.

Examples
This example creates an anonymous function that greets a person by name and then calls it.
PHP
<?php
$greet = function($name) {
    return "Hello, $name!";
};

echo $greet("Alice");
This anonymous function adds two numbers and returns the result.
PHP
<?php
$sum = function($a, $b) {
    return $a + $b;
};

echo $sum(3, 4);
This example shows how to use a variable from outside the function using use.
PHP
<?php
$message = "Hi";

$showMessage = function() use ($message) {
    echo $message;
};

$showMessage();
Sample Program

This program defines an anonymous function to multiply two numbers, calls it with 5 and 6, and prints the result.

PHP
<?php
// Create an anonymous function to multiply two numbers
$multiply = function($x, $y) {
    return $x * $y;
};

// Call the function and print the result
$result = $multiply(5, 6);
echo "5 times 6 is $result";
OutputSuccess
Important Notes

Remember to add a semicolon ; after the anonymous function definition when assigning it to a variable.

Anonymous functions can be stored in variables, passed as arguments, or returned from other functions.

Summary

Anonymous functions are unnamed functions assigned to variables.

They are useful for quick, one-time use functions or callbacks.

You can access outside variables inside anonymous functions using use.