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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate 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;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting