June 13, 2021

Closure in JavaScript vs PHP β€” What’s the Difference?


βœ… What is a Closure (in both)?

A closure is a function that captures variables from its surrounding scope and can use them even after the outer function has finished.

But the syntax and behavior differ between JavaScript and PHP.


πŸ“˜ JavaScript Closures

βœ… Syntax Example:

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}

const counter = outer();
counter(); // 1
counter(); // 2

βœ… inner() remembers count, even after outer() has returned β€” this is a closure.

πŸ”Ή JS Closures:

  • Created when an inner function uses variables from the outer scope.
  • Supports lexical scoping.
  • Widely used in async callbacks, event handling, functional programming, etc.
  • Captured variables are still live in memory.

🐘 PHP Closures

βœ… Syntax Example:

function outer() {
  $count = 0;
  return function () use (&$count) {
    $count++;
    echo $count . PHP_EOL;
  };
}

$counter = outer();
$counter(); // 1
$counter(); // 2

βœ… In PHP, closures must explicitly import variables using the use keyword.

πŸ”Ή PHP Closures:

  • Created with function() use ($var) syntax.
  • Variables are not automatically captured β€” you must declare them.
  • Can pass by value or by reference (&).
  • Often used in array functions (array_map, array_filter), dependency injection, or functional-style code.

βš–οΈ Key Differences: JS vs PHP Closure

FeatureJavaScriptPHP
Variable captureAutomatic (lexical scope)Manual (use keyword)
Reference captureAlways by referenceUse & for reference explicitly
Function syntaxfunction(){} or arrow ()=>{}function() use ($x) {}
Common use casesCallbacks, event handlers, promisesArray functions, DI, callbacks
Memory lifetimeCaptured variables stay aliveSimilar, but more manual
Functional programmingFully supportedPartially supported

πŸ“ Summary (Easy to Remember)

JavaScriptPHP
Closures = common, autoClosures = manual, explicit
Inner function captures outer scopeuse is required
Great for async and dynamic behaviorGreat for callbacks and short logic
Implicit referencesExplicit references via &

πŸ’¬ Final Thoughts

In JavaScript, closures are natural and automatic.
In PHP, closures are explicit and controlled, using use() to bring in variables.

Both are useful, just different in style and usage.