Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

PHP closures are very simple

Parent Feed: 

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, ...)
Author: 
RSS Tags: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web