What are the differences between closures in JS and closures in PHP? Do they pretty much work the same way? Are there any caveats to be aware of when writing closures in PHP?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One difference is how both cope with storing the context in which an anonymous function is executed:
To fix this notice you’ll have to use the
usesyntax:To have the anonymous function behave somehow like the JavaScript counterpart you’ll have to use references:
I think this is the most striking difference between JavaScript and PHP closures.
Second difference is that every JavaScript closure has a
thiscontext available which means, that you can usethisinside the closure itself (although it’s often quite complicated to figure out whatthisactually refers to) – PHP’s current stable version (PHP 5.3) does not yet support$thisinside a closure, but PHP’s upcoming version (PHP 5.4) will support$thisbinding and rebinding using$closure->bind($this)(See the Object Extension RFC for more info.)Third difference is how both languages treat closures assigned to object properties:
The same is true if closures are assigned to properties in class definitions:
Fourth difference: JavaScript Closures are full fledged objects, wheres in PHP they are restricted objects. For instance, PHP Closures cannot have properties of their own:
while in JavaScript you can do:
Fifth difference: Returned closures can be immediately called upon in Javascript:
Not in PHP: