Warning: Trying to access array offset on value of type null in /home/uhmn6p9kb8ir/public_html/soatechnology/wp-content/themes/bluecollar/index.php on line 17
Advanced topics (anonymous functions, closures, arrow functions) | Website Development, Application Development, Online Internship, Online Class, Work from home, Learn Programming Online

📲 Download Utility Tools Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

Advanced topics (anonymous functions, closures, arrow functions)

🔥 1. Anonymous Functions (Closures Basics)

👉 Anonymous functions = functions without a name

✅ Syntax:

$func = function() {
echo "Hello World";
};$func(); // call it

👉 You store the function in a variable and then call it.


✅ With Parameters:

$sum = function($a, $b) {
return $a + $b;
};echo $sum(5, 3);

📌 Where used in real life:

  • Callbacks
  • Array functions (array_map, array_filter)
  • Event handling

✅ Example with array:

$numbers = [1, 2, 3];$result = array_map(function($n) {
return $n * 2;
}, $numbers);print_r($result);

🔥 2. Closures (Very Important)

👉 A closure is an anonymous function that can access variables from outside using use.


❗ Problem (Without Closure)

$msg = "Hello";$func = function() {
echo $msg; // ❌ Error (undefined)
};

✅ Solution (Using use)

$msg = "Hello";$func = function() use ($msg) {
echo $msg;
};$func();

🔁 Pass by Reference in Closure

$count = 0;$increment = function() use (&$count) {
$count++;
};$increment();
$increment();echo $count; // 2

📌 Real Use Case:

  • Capturing environment variables
  • Middleware (Laravel, Express-like logic)
  • Custom callbacks

🔥 3. Arrow Functions (PHP 7.4+)

👉 Short syntax for writing functions


✅ Syntax:

$sum = fn($a, $b) => $a + $b;

✅ Example:

echo $sum(10, 5);

📌 Key Difference from Closure:

FeatureClosureArrow Function
SyntaxLongShort
use keywordRequiredNot needed
ScopeManualAutomatic

✅ Example with array:

$nums = [1, 2, 3];$result = array_map(fn($n) => $n * 3, $nums);print_r($result);

⚠️ Important Differences

🔸 Closure vs Arrow Function

👉 Closure:

$x = 5;$func = function() use ($x) {
return $x * 2;
};

👉 Arrow:

$x = 5;$func = fn() => $x * 2;

🔸 Limitation of Arrow Function

👉 Only single expression allowed

❌ Not allowed:

fn($x) => {
$y = $x * 2;
return $y;
};

💡 Real-World Examples


✅ 1. Filter Even Numbers

$nums = [1,2,3,4,5,6];$even = array_filter($nums, fn($n) => $n % 2 == 0);print_r($even);

✅ 2. Custom Sorting

$users = [
["name" => "A", "age" => 25],
["name" => "B", "age" => 20]
];usort($users, fn($a, $b) => $a['age'] <=> $b['age']);print_r($users);

✅ 3. Simple Middleware (Concept)

function middleware($next) {
return function($request) use ($next) {
echo "Before\n";
$next($request);
echo "After\n";
};
}

🧠 Interview-Level Insights

👉 Interviewers may ask:

❓ Why use closures?

  • Encapsulation
  • Cleaner callbacks
  • Avoid global variables

❓ Arrow vs Closure?

👉 Arrow:

  • Short
  • Automatic variable capture

👉 Closure:

  • More powerful
  • Supports multiple statements

❓ When NOT to use arrow functions?

  • When logic is complex
  • When multiple statements needed
  • When modifying external variables

🎯 Practice Questions

Try these:

  1. Use array_map with arrow function to square numbers
  2. Create closure that counts function calls
  3. Build a custom filter function
  4. Sort array of objects using closure
  5. Create a function that returns another function (closure)


AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes