0
0
PHPprogramming~15 mins

First-class callable syntax in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using First-class Callable Syntax in PHP
📖 Scenario: Imagine you are building a simple PHP program that processes a list of numbers by applying a function to each number. You want to use PHP's first-class callable syntax to pass functions easily.
🎯 Goal: You will create a list of numbers, define a function to double a number, use first-class callable syntax to apply this function to each number, and then print the results.
📋 What You'll Learn
Create an array called numbers with the values 1, 2, 3, 4, 5.
Create a function called double that takes one parameter and returns its value multiplied by 2.
Create a variable called doubleFunc that stores the first-class callable syntax for the double function.
Use array_map with doubleFunc to create a new array called doubledNumbers.
Print the doubledNumbers array using print_r.
💡 Why This Matters
🌍 Real World
First-class callable syntax helps you pass functions around easily, making your code cleaner and more flexible when processing data.
💼 Career
Understanding first-class callables is useful for PHP developers working on modern codebases, especially when using functional programming techniques or frameworks.
Progress0 / 4 steps
1
Create the numbers array
Create an array called numbers with the values 1, 2, 3, 4, 5.
PHP
Need a hint?

Use square brackets [] to create an array in PHP.

2
Define the doubling function
Create a function called double that takes one parameter $n and returns $n * 2.
PHP
Need a hint?

Define a function using the function keyword and return the doubled value.

3
Create the first-class callable variable
Create a variable called doubleFunc that stores the first-class callable syntax for the double function using double(...).
PHP
Need a hint?

Use double(...) to get the first-class callable and assign it to $doubleFunc.

4
Apply the function and print results
Use array_map with $doubleFunc and $numbers to create a new array called doubledNumbers. Then print doubledNumbers using print_r.
PHP
Need a hint?

Use array_map($doubleFunc, $numbers) to apply the function to each number.