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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- Laravel Option Select - Default Issue
- How to toggle on Order in ReactJS
- PHP Recursively File Folder Scan Sorted by Modific
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
use
syntax: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
this
context available which means, that you can usethis
inside the closure itself (although it's often quite complicated to figure out whatthis
actually refers to) - PHP's current stable version (PHP 5.3) does not yet support$this
inside a closure, but PHP's upcoming version (PHP 5.4) will support$this
binding 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:
They do pretty much work the same way. Here's more information about the PHP implementation: http://php.net/manual/en/functions.anonymous.php
You can use a closure (in PHP called 'anonymous function') as a callback:
and assign it to a variable:
Furthermore, anonymous function 'inherit' the scope in which they were defined - just as the JS implementation, with one gotcha: you have to list all variables you want to inherit in a
use()
:and as a reference if you want to modify the orignal variable.
The only thing I've found in PHP (that is totally cool and really handy!) is the ability to use them as getters and setters in classes which was always a nightmare to achieve before, JavaScript can be used in the same way but they do both act almost identically from what I've seen.
I'm not sure about the namespacing convention differences between the two but as @Rijk pointed out there is a section on the PHP website dedicated to them
They are also really great for...
Looping through items with a controller rather than a new for/each loop on the page
Great for supplying as arguments to functions/classes
Whats annoying about them is...
You can't typecast them, since they're just functions...