Menu
Coddy logo textTech

Anonymous Functions

Part of the Logic & Flow section of Coddy's PHP journey — lesson 1 of 68.

Anonymous functions, also known as closures, are functions without a specified name. They're perfect for short, one-off tasks where creating a full named function would be overkill.

To create an anonymous function, you use the function keyword without a function name, then assign it to a variable:

<?php
$greeting = function($name) {
    echo "Hello, " . $name . "!";
};
?>

Notice the semicolon after the closing brace - this is required because you're assigning the function to a variable.

To call the anonymous function, you use the variable name followed by parentheses:

<?php
$greeting("Alice");  // Outputs: Hello, Alice!
?>

Anonymous functions are particularly useful when you need a simple function for a specific task without cluttering your code with named functions you'll only use once.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create an anonymous function that takes a number as a parameter and returns the square of that number. Assign this function to a variable called $square.

You will receive a number as input. Read the number, call your anonymous function with this number, and print the result.

Input format: A single number (which may contain decimals)

Expected output: The square of the input number

Cheat sheet

Anonymous functions (closures) are functions without a specified name, useful for short, one-off tasks.

Create an anonymous function using the function keyword without a name, then assign it to a variable:

<?php
$greeting = function($name) {
    echo "Hello, " . $name . "!";
};
?>

Note the semicolon after the closing brace is required when assigning a function to a variable.

Call the anonymous function using the variable name followed by parentheses:

<?php
$greeting("Alice");  // Outputs: Hello, Alice!
?>

Try it yourself

<?php
// Read input
$number = floatval(fgets(STDIN));

// TODO: Create an anonymous function and assign it to $square variable


// Call the function and print the result
echo $square($number);
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow