📖 Scenario: Imagine you are building a simple PHP program to manage a list of tasks. You want to create a way to filter tasks based on their priority using a special function that remembers the priority level you want to filter by. This is where closures in PHP become very useful.
🎯 Goal: You will create a closure in PHP that remembers a priority level and then use it to filter tasks. This will show why closures matter: they let you keep some data inside a function for later use.
📋 What You'll Learn
Create an array called $tasks with specific tasks and their priorities
Create a variable called $priorityFilter to hold the priority level to filter
Create a closure called $filterTasks that uses use to remember $priorityFilter
Use array_filter with $filterTasks to get tasks matching the priority
Print the filtered tasks
💡 Why This Matters
🌍 Real World
Closures help keep some data inside a function, which is useful when you want to create small, reusable pieces of code that remember settings or filters. This is common in web apps, data processing, and event handling.
💼 Career
Understanding closures is important for PHP developers because many modern PHP frameworks and libraries use closures for callbacks, event listeners, and filtering data efficiently.
Progress0 / 4 steps
1
Create the tasks array
Create an array called $tasks with these exact entries: 'Buy groceries' => 'high', 'Clean house' => 'low', 'Pay bills' => 'medium', 'Call mom' => 'high'.
PHP
Hint
Use square brackets [] to create the array with keys and values.
2
Set the priority filter
Create a variable called $priorityFilter and set it to the string 'high'.
PHP
Hint
Use = to assign the string 'high' to $priorityFilter.
3
Create the closure to filter tasks
Create a closure called $filterTasks that takes one parameter $priority and uses use ($priorityFilter) to remember the $priorityFilter variable. The closure should return true if $priority equals $priorityFilter, otherwise false.
PHP
Hint
Use function($priority) use ($priorityFilter) to create the closure that remembers $priorityFilter.
4
Filter and print the tasks
Use array_filter with $tasks and $filterTasks to create a new array called $filteredTasks. Then print $filteredTasks using print_r.
PHP
Hint
Use array_filter($tasks, $filterTasks) to get tasks with priority 'high'. Then use print_r to display the filtered tasks.
Practice
(1/5)
1. What is a closure in PHP?
easy
A. A named function that cannot access outside variables
B. An anonymous function that can access variables from its parent scope
C. A class method that is always static
D. A variable that stores a string value
Solution
Step 1: Understand the definition of closure and compare options
A closure is an anonymous function that can remember and use variables from the scope where it was created. Only An anonymous function that can access variables from its parent scope describes an anonymous function with access to outer variables, which matches the closure concept.
Final Answer:
An anonymous function that can access variables from its parent scope -> Option B
Quick Check:
Closure = Anonymous function with outer scope access [OK]
Hint: Closures are anonymous functions with memory of outside variables [OK]
Common Mistakes:
Confusing closures with regular named functions
Thinking closures cannot access outside variables
Mixing closures with class methods
2. Which of the following is the correct syntax to create a closure in PHP?
easy
A. $func = closure() { echo 'Hello'; };
B. function $func() { echo 'Hello'; };
C. $func = function() { echo 'Hello'; };
D. $func = new function() { echo 'Hello'; };
Solution
Step 1: Recall PHP closure syntax and check options
Closures are created using the keyword function without a name, assigned to a variable. $func = function() { echo 'Hello'; }; uses function() { ... } assigned to $func, which is correct syntax.
Final Answer:
$func = function() { echo 'Hello'; }; -> Option C
Quick Check:
Closure syntax = function() { ... } [OK]
Hint: Closures use 'function() { }' assigned to variables [OK]
Step 1: Understand the use keyword and trace execution
The closure uses use ($message) to import the variable $message from the outer scope. When $greet() is called, it echoes the value of $message, which is 'Hi'.
Final Answer:
Hi -> Option D
Quick Check:
Closure with use outputs outer variable value [OK]
Hint: Closures use 'use' to access outside variables [OK]
Common Mistakes:
Forgetting to use 'use' keyword to import variables
Expecting closure to access outer variables automatically
A. Closure cannot access $count without 'use' keyword
B. Syntax error: missing semicolon after function
C. Cannot increment variables inside closures
D. No error, outputs 1
Solution
Step 1: Analyze variable access and PHP scope rules in closures
The closure tries to increment $count but does not import it with use, so $count is undefined inside. Variables outside closures must be imported with use to be accessible inside closures.
Final Answer:
Closure cannot access $count without 'use' keyword -> Option A
Quick Check:
Use 'use' to access outer variables inside closures [OK]
Hint: Always import outer variables with 'use' in closures [OK]
Thinking increment inside closure changes outer variable without 'use'
Confusing syntax errors with scope errors
5. How can closures help in creating private data in PHP? Choose the best explanation.
hard
A. Closures can capture variables in their scope, hiding them from outside access
B. Closures automatically make variables global
C. Closures convert variables to constants
D. Closures prevent any function from accessing variables
Solution
Step 1: Understand private data and how closures enable it
Private data means variables that cannot be accessed directly from outside code. Closures can enclose variables in their scope, so only the closure can access or modify them, hiding them from outside.
Final Answer:
Closures can capture variables in their scope, hiding them from outside access -> Option A
Quick Check:
Closures enable private data by capturing variables [OK]
Hint: Closures hide variables by capturing them inside functions [OK]
Common Mistakes:
Thinking closures make variables global
Confusing closures with constants
Believing closures block all variable access
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.