Menu
Coddy logo textTech

Closures and 'use'

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

By default, anonymous functions can only access variables that are passed to them as parameters. But what if you need your closure to access a variable from the surrounding scope? This is where the use keyword comes in.

The use keyword allows a closure to "capture" variables from its parent scope and use them inside the function:

<?php
$message = "Welcome";

$greeting = function($name) use ($message) {
    echo $message . ", " . $name . "!";
};

$greeting("Bob");  // Outputs: Welcome, Bob!
?>

Notice how $message is defined outside the function, but by including use ($message) after the parameter list, the closure can access and use that variable. You can capture multiple variables by separating them with commas: use ($var1, $var2).

This feature makes closures much more powerful, allowing them to work with data from their surrounding context while still maintaining the flexibility of anonymous functions.

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 captures a discount percentage from the surrounding scope using the use keyword. The function should take a price as a parameter and return the final price after applying the discount.

You will receive two inputs: the discount percentage and the original price. Read both inputs, create a closure that captures the discount percentage, call the closure with the price, and print the final price after discount.

Input format: Two lines - first line contains the discount percentage (a number), second line contains the original price (a number which may contain decimals)

Expected output: The final price after applying the discount

Cheat sheet

The use keyword allows closures to capture variables from their parent scope:

<?php
$message = "Welcome";

$greeting = function($name) use ($message) {
    echo $message . ", " . $name . "!";
};

$greeting("Bob");  // Outputs: Welcome, Bob!
?>

You can capture multiple variables by separating them with commas: use ($var1, $var2).

Try it yourself

<?php
// Read inputs
$discount = floatval(fgets(STDIN));
$price = floatval(fgets(STDIN));

// TODO: Create an anonymous function that captures the discount percentage using 'use'
// The function should take a price parameter and return the final price after discount


// TODO: Call the closure with the price and store the result


// Output the final price
echo $finalPrice;
?>
quiz iconTest yourself

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

All lessons in Logic & Flow