Middle
What is the difference between closures in PHP and JavaScript?
sobes.tech AI
Answer from AI
The key difference lies in how they are created and used:
- PHP: Closures are objects of the class
Closure. They are created using thefunctionkeyword (for anonymous functions) and can explicitly import variables from the parent scope using theusekeyword. Variables are imported by value by default, but references (&) can be used for import by reference. - JavaScript: Closures are naturally created when defining a function inside another function. The inner function has access to the variables of the outer function and its scope. Variables are captured by reference (or by value for primitive types and copying).
In PHP, closures are more explicit thanks to the use syntax, whereas in JavaScript, this mechanism is more transparent to the developer.
Example in PHP:
<?php
function outerFunction($x) {
return function() use ($x) { // Explicit import of $x
echo $x;
};
}
$closure = outerFunction("Hello");
$closure(); // Output: Hello
Example in JavaScript:
function outerFunction(x) {
return function() { // Implicit access to x
console.log(x);
};
}
const closure = outerFunction("Hello");
closure(); // Output: Hello