Closures seem like big magic but in PHP they are just syntactic sugar over the following construct:
<?php
class OurClosure {
function __construct($add) {
$this->add = $add;
}
function __invoke($x) {
print $x + $this->add;
print "\n";
}
}
$print_add_2 = new OurClosure(2); // call __construct
$print_add_2(5); // when an object is called like a function it calls __invoke
?>
Now, closures use the following syntax:
<?php
function get_add_printer($add) {
return function ($x) use ($add) {
print $x + $add;
print "\n";
};
}
$print_add_2 = get_add_printer(2);
$print_add_2(5);
?>
This is the exact same -- it's internally implemented exactly like that:
function ($ARG1_TO_BE_USED_WHEN_CALLING_INVOKE, $ARG2_TO_BE_USED_WHEN_CALLING_INVOKE, ...) use ($ARG1_TO_STORE_IN_CONSTRUCT, $ARG2_TO_STORE_IN_CONSTRUCT, ...)
Commenting on this Story is closed.
Thanks for the nice and concise example!
For more information and examples of Closures and friends, see the excellent session at DrupalCon Munich by Crell: http://munich2012.drupal.org/program/sessions/functional-php
Ugly object oriented code :)
Call me old fashioned, but I consider spaghetti code and simple functions much more readable...
Probably D8 wont be for me if this is what awaits devs.
Cheers
giorgio79
Because I was like that too. But consider two things a) the last time Drupal had simple functions was perhaps 4.4, maybe 4.6 definitely not since. Also, often OOP allows for much better IDE support and that makes it easier.
OOP is definitely (when appropriate) cleaner and more straightforward than procedural code. The continued movement with this in D7 and more through D8 should really help development of more advanced capabilities and ideas via better/tighter APIs. Sometimes it seems like procedural is alright, until you wind up with a few thousand lines before you realize it, opening up all sorts of issues depending on what you're working on.
Also, like he said, IDE support for OOP far surpasses just straight procedural, especially if you're using an IDE like PHPStorm.
I second it.
We're not doing a ton of anonymous functions at this point, and likely won't be making heavy use of them. They are used in a few places, though. That's functional programming, not OO.
That said, if you want code that is just a series of functions calling each other at random times that makes debugging impossible with global state hanging around that could change out from under you at any time... you're right. Drupal 8 is not for you.
"That said, if you want code that is just a series of functions calling each other at random times that makes debugging impossible with global state hanging around that could change out from under you at any time... you're right. Drupal 8 is not for you."
If you want code that is just a series of objects referencing, inheriting, polymorhphing, encapsulating (did I miss something?) each other that makes reading code impossible than go for it...
Real code?