SlideShare a Scribd company logo
Anonymous Functions in PHP 5.3

      Matthew Weier O’Phinney

            26 April 2011
But first, some vocabulary
Lambdas

   • From “lambda calculus”




26 April 2011      Anonymous Functions in PHP 5.3   3
Lambdas

   • From “lambda calculus”
   • Names of functions are merely a “convenience”, and
     hence all functions are considered anonymous




26 April 2011       Anonymous Functions in PHP 5.3        3
Lambdas

   • From “lambda calculus”
   • Names of functions are merely a “convenience”, and
     hence all functions are considered anonymous
   • Unless you’re using a true functional programming
     language with first-class functions, most likely you’re
     simply using anonymous functions, or lambda
     expressions.




26 April 2011        Anonymous Functions in PHP 5.3           3
Closures

   • A function which includes a referencing environment




26 April 2011       Anonymous Functions in PHP 5.3         4
Closures

   • A function which includes a referencing environment
         • Each function has its own scope
         • Allows hiding state




26 April 2011          Anonymous Functions in PHP 5.3      4
Closures

   • A function which includes a referencing environment
         • Each function has its own scope
         • Allows hiding state
   • Differentiating factor is that closures allow binding
     references that exist at the time of creation, to use
     when called.




26 April 2011          Anonymous Functions in PHP 5.3        4
Anonymous Functions

   • Any function defined and/or called without being
     bound to an identifier.
         • You can assign the function to a variable, but
           you’re not giving it its own name.




26 April 2011           Anonymous Functions in PHP 5.3      5
PHP’s Offering
Functors

   • Any object defining a __invoke() method.
   • Object instances can now be called as if they were
     functions.


      class Command
      {
          public function __invoke($name)
          {
              echo "Hello, $name";
          }
      }
      $c = new Command();
      $c(’Matthew’); // "Hello, Matthew"




26 April 2011               Anonymous Functions in PHP 5.3   7
Anonymous Functions

   • new Closure class, which defines __invoke().




26 April 2011     Anonymous Functions in PHP 5.3   8
Anonymous Functions

   • new Closure class, which defines __invoke().
   • __invoke() body is “replaced” with the defined
     function.




26 April 2011      Anonymous Functions in PHP 5.3    8
Anonymous Functions

   • new Closure class, which defines __invoke().
   • __invoke() body is “replaced” with the defined
     function.
   • Ability to bind variables via imports, allowing creation
     of closures.




26 April 2011         Anonymous Functions in PHP 5.3            8
Important to know:

   • Just like normal PHP functions, anonymous
     functions exist in their own scope.




26 April 2011       Anonymous Functions in PHP 5.3   9
Important to know:

   • Just like normal PHP functions, anonymous
     functions exist in their own scope.
   • You cannot import $this.




26 April 2011       Anonymous Functions in PHP 5.3   9
Important to know:

   • Just like normal PHP functions, anonymous
     functions exist in their own scope.
   • You cannot import $this.
   • You cannot alias imported variables.




26 April 2011       Anonymous Functions in PHP 5.3   9
Anonymous Function and
    Closure Syntax
Basics

   • Simply like normal function declaration, except no
     name:


      function($value1[, $value2[, ... $valueN]]) { };




26 April 2011               Anonymous Functions in PHP 5.3   11
Assign to variables

   • Assign functions to variables; don’t forget the
     semicolon terminator!


      $greet = function($name) {
          echo "Hello, $name";
      };

      $greet(’Matthew’); // "Hello, Matthew"




26 April 2011               Anonymous Functions in PHP 5.3   12
Pass as arguments to other callables

   • Allow other functionality to call the function.


      function say($value, $callback)
      {
          echo $callback($value);
      }

      say(’Matthew’, function($name) {
          return "Hello, $name";
      }); // "Hello, Matthew"




26 April 2011               Anonymous Functions in PHP 5.3   13
Create closures

   • Bind variables at creation, and use them at call-time.


      $log = Zend_Log::factory($config);

      $logger = function() use($log) {
          $args = func_get_args();
          $log->info(json_encode($args));
      };

      $logger(’foo’, ’bar’); // ["foo", "bar"]




26 April 2011               Anonymous Functions in PHP 5.3    14
Things to try
Array operations

   • Sorting (usort, uasort, etc.)
   • Walking, mapping, reducing
   • Filtering




26 April 2011         Anonymous Functions in PHP 5.3   16
Sorting


      $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);
      usort($stuff, function($a, $b) {
          return strcasecmp($a, $b);
      });
      // ’Anise’, ’apple’, ’Applesauce’, ’appleseed’




26 April 2011               Anonymous Functions in PHP 5.3           17
Walking

   • Walking allows you to change the values of an array.




26 April 2011        Anonymous Functions in PHP 5.3         18
Walking

   • Walking allows you to change the values of an array.
   • If not using objects, then you need to pass by
     reference in order to alter values.


      $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);
      array_walk($stuff, function(&$value) {
          $value = strtoupper($value);
      });
      // ’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’




26 April 2011               Anonymous Functions in PHP 5.3           18
Mapping

   • Mapping performs work on each element, resulting
     in a new array with the values returned.




26 April 2011       Anonymous Functions in PHP 5.3      19
Mapping

   • Mapping performs work on each element, resulting
     in a new array with the values returned.


      $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);
      $mapped = array_map(function($value) {
          $value = strtoupper($value);
          return $value;
      }, $stuff);
      // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)
      // $mapped: array(’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’)




26 April 2011               Anonymous Functions in PHP 5.3             19
Reducing

   • “Combine” elements and return a value or data set.




26 April 2011       Anonymous Functions in PHP 5.3        20
Reducing

   • “Combine” elements and return a value or data set.
   • Return value is passed as first argument of next call.




26 April 2011        Anonymous Functions in PHP 5.3          20
Reducing

   • “Combine” elements and return a value or data set.
   • Return value is passed as first argument of next call.
   • Seed the return value by passing a third argument to
     array_reduce().


      $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);
      $reduce = array_reduce($stuff, function($count, $input) {
          $count += substr_count($input, ’a’);
          return $count;
      }, 0);
      // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)
      // $reduce: 3




26 April 2011               Anonymous Functions in PHP 5.3            20
Filtering

   • Return only the elements that evaluate to true.




26 April 2011        Anonymous Functions in PHP 5.3    21
Filtering

   • Return only the elements that evaluate to true.
   • Often, this is a form of mapping, and used to trim a
     dataset to only those of interest prior to reducing.


      $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);
      $reduce = array_reduce($stuff, function($count, $input) {
          $count += substr_count($input, ’a’);
          return $count;
      }, 0);
      // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)
      // $reduce: 3




26 April 2011               Anonymous Functions in PHP 5.3            21
String operations

   • Regular expressions (preg_replace_callback)




26 April 2011      Anonymous Functions in PHP 5.3   22
String operations

   • Regular expressions (preg_replace_callback)
   • Currying arguments




26 April 2011      Anonymous Functions in PHP 5.3   22
preg_replace_callback()

   • Allows you to transform captured matches.


      $string = "Today’s date next month is " . date(’Y-m-d’);
      $fixed = preg_replace_callback(’/(d{4}-d{2}-d{2})/’,
      function($matches) {
          $date = new DateTime($matches[1]);
          $date->add(new DateInterval(’P1M’));
          return $date->format(’Y-m-d’);
      }, $string);
      // "Today’s date next month is 2011-05-26"




26 April 2011               Anonymous Functions in PHP 5.3       23
Currying arguments

   • In some cases, you may want to provide default
     arguments:




26 April 2011       Anonymous Functions in PHP 5.3    24
Currying arguments

   • In some cases, you may want to provide default
     arguments:
         • To reduce the number of arguments needed.




26 April 2011         Anonymous Functions in PHP 5.3   24
Currying arguments

   • In some cases, you may want to provide default
     arguments:
         • To reduce the number of arguments needed.
         • To supply values for optional arguments.




26 April 2011         Anonymous Functions in PHP 5.3   24
Currying arguments

   • In some cases, you may want to provide default
     arguments:
         • To reduce the number of arguments needed.
         • To supply values for optional arguments.
         • To provide a unified signature for callbacks.




26 April 2011          Anonymous Functions in PHP 5.3     24
Currying arguments

   • In some cases, you may want to provide default
     arguments:
         • To reduce the number of arguments needed.
         • To supply values for optional arguments.
         • To provide a unified signature for callbacks.


      $hs = function ($value) {
          return htmlspecialchars($value, ENT_QUOTES, "UTF-8", false);
      };
      $filtered = $hs("<span>Matthew Weier O’Phinney</span>");
      // "&lt;span&gt;Matthew Weier O&#039;Phinney&lt;/span&gt;"




26 April 2011               Anonymous Functions in PHP 5.3               24
Gotchas
References

   • Variables passed to callbacks, either as arguments
     or imports, are not passed by reference.




26 April 2011       Anonymous Functions in PHP 5.3        26
References

   • Variables passed to callbacks, either as arguments
     or imports, are not passed by reference.
         • Use objects, or




26 April 2011          Anonymous Functions in PHP 5.3     26
References

   • Variables passed to callbacks, either as arguments
     or imports, are not passed by reference.
         • Use objects, or
         • Pass by reference




26 April 2011         Anonymous Functions in PHP 5.3      26
References

   • Variables passed to callbacks, either as arguments
     or imports, are not passed by reference.
         • Use objects, or
         • Pass by reference


      $count   = 0;
      $counter = function (&$value) use (&$count) {
          if (is_int($value)) {
              $count += $value;
              $value = 0;
          }
      };
      $stuff = array(’foo’, 1, 3, ’bar’);
      array_walk($stuff, $counter);
      // $stuff: array(’foo’, 0, 0, ’bar’)
      // $count: 4



26 April 2011               Anonymous Functions in PHP 5.3   26
Mixing with other callables

   Problems and considerations:
   • Closure is an “implementation detail”; typehinting
     on it excludes other callback types.




26 April 2011        Anonymous Functions in PHP 5.3       27
Mixing with other callables

   Problems and considerations:
   • Closure is an “implementation detail”; typehinting
     on it excludes other callback types.
   • is_callable() tells us only that it can be called,
     not how.




26 April 2011       Anonymous Functions in PHP 5.3        27
Mixing with other callables

   Problems and considerations:
   • Closure is an “implementation detail”; typehinting
     on it excludes other callback types.
   • is_callable() tells us only that it can be called,
     not how.
   • is_callable() && is_object() tells us we
     have a functor, but omits other callback types.




26 April 2011       Anonymous Functions in PHP 5.3        27
Mixing with other callables

   Three ways to call (1/3):
   • $o($arg1, $arg2)




26 April 2011         Anonymous Functions in PHP 5.3   28
Mixing with other callables

   Three ways to call (1/3):
   • $o($arg1, $arg2)
         • Benefits: speed.




26 April 2011         Anonymous Functions in PHP 5.3   28
Mixing with other callables

   Three ways to call (1/3):
   • $o($arg1, $arg2)
         • Benefits: speed.
         • Problems: won’t work unless we have a functor,
           closure, or static method call.




26 April 2011          Anonymous Functions in PHP 5.3       28
Mixing with other callables

   Three ways to call (2/3):
   • call_user_func($o, $arg1, $arg2)




26 April 2011         Anonymous Functions in PHP 5.3   29
Mixing with other callables

   Three ways to call (2/3):
   • call_user_func($o, $arg1, $arg2)
         • Benefits: speed, works with all callables.




26 April 2011           Anonymous Functions in PHP 5.3   29
Mixing with other callables

   Three ways to call (2/3):
   • call_user_func($o, $arg1, $arg2)
         • Benefits: speed, works with all callables.
         • Problems: if number of arguments are unknown
           until runtime, this gets difficult.




26 April 2011         Anonymous Functions in PHP 5.3      29
Mixing with other callables

   Three ways to call (3/3):
   • call_user_func_array($o, $argv)




26 April 2011         Anonymous Functions in PHP 5.3   30
Mixing with other callables

   Three ways to call (3/3):
   • call_user_func_array($o, $argv)
         • Benefits: works with all callables., works with
           variable argument counts.




26 April 2011           Anonymous Functions in PHP 5.3      30
Mixing with other callables

   Three ways to call (3/3):
   • call_user_func_array($o, $argv)
         • Benefits: works with all callables., works with
           variable argument counts.
         • Problems: speed (takes up to 6x longer to
           execute than straight call).




26 April 2011           Anonymous Functions in PHP 5.3      30
You cannot import $this

   • Creative developers will want to use closures to
     monkey-patch objects.




26 April 2011        Anonymous Functions in PHP 5.3     31
You cannot import $this

   • Creative developers will want to use closures to
     monkey-patch objects.
   • You can. You just can’t use $this, which means
     you’re limited to public methods.




26 April 2011       Anonymous Functions in PHP 5.3      31
You cannot import $this

   • Creative developers will want to use closures to
     monkey-patch objects.
   • You can. You just can’t use $this, which means
     you’re limited to public methods.
   • Also, you can’t auto-dereference closures assigned
     to properties.




26 April 2011       Anonymous Functions in PHP 5.3        31
Example: Monkey-Patching


      class Foo
      {
          public function __construct()
          {
              $self = $this;
              $this->bar = function () use ($self) {
                  return get_object_vars($self);
              };
          }

           public function addMethod($name, Closure $c)
           {
               $this->$name = $c;
           }

          public function __call($method, $args)
          {
              if (property_exists($this, $method) &&
      is_callable($this->$method)) {
                  return call_user_func_array($this->$method, $args);
              }
          }
      }

26 April 2011                Anonymous Functions in PHP 5.3             32
Serialization

   • You can’t serialize anonymous functions.




26 April 2011       Anonymous Functions in PHP 5.3   33
Some Use Cases
Aspect Oriented Programming

   • Code defines “aspects,” or code that cuts across
     boundaries of many components.




26 April 2011       Anonymous Functions in PHP 5.3     35
Aspect Oriented Programming

   • Code defines “aspects,” or code that cuts across
     boundaries of many components.
   • AOP formalizes a way to join aspects to other code.




26 April 2011        Anonymous Functions in PHP 5.3        35
Aspect Oriented Programming

   • Code defines “aspects,” or code that cuts across
     boundaries of many components.
   • AOP formalizes a way to join aspects to other code.
   • Often, you will need to curry arguments in order to
     maintain signatures.




26 April 2011        Anonymous Functions in PHP 5.3        35
Event Management example


      $front->events()->attach(’dispatch.router.post’, function($e) use
      ($cache) {
          $request = $e->getParam(’request’);
          if (!$request instanceof ZendHttpRequest || !$request->isGet())
      {
              return;
          }

            $metadata = json_encode($request->getMetadata());
            $key      = hash(’md5’, $metadata);
            $backend = $cache->getCache(’default’);
            if (false !== ($content = $backend->load($key))) {
                $response = $e->getParam(’response’);
                $response->setContent($content);
                return $response;
            }
            return;
      });




26 April 2011                 Anonymous Functions in PHP 5.3                  36
That’s all, folks!
References

   • PHP Manual:
     http://php.net/functions.anonymous




26 April 2011   Anonymous Functions in PHP 5.3   38
Thank You!

More Related Content

PPT
Php Chapter 2 3 Training
PDF
PHP Unit 3 functions_in_php_2
PPT
Functions in php
PPT
Class 3 - PHP Functions
PPT
php 2 Function creating, calling, PHP built-in function
PPTX
Arrays &amp; functions in php
PPTX
Introduction in php
PPTX
Introduction in php part 2
Php Chapter 2 3 Training
PHP Unit 3 functions_in_php_2
Functions in php
Class 3 - PHP Functions
php 2 Function creating, calling, PHP built-in function
Arrays &amp; functions in php
Introduction in php
Introduction in php part 2

What's hot (20)

PPTX
Object-Oriented Programming with PHP (part 1)
PPT
Class 2 - Introduction to PHP
PDF
Functions in PHP
PDF
Php Tutorials for Beginners
PPTX
PHP Basics
PDF
DIG1108 Lesson 6
PPTX
PHP function
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PDF
PHP Enums - PHPCon Japan 2021
PDF
Typed Properties and more: What's coming in PHP 7.4?
PDF
PHP 8.1 - What's new and changed
PDF
4.2 PHP Function
PDF
Operators in PHP
PPTX
Subroutines
PPT
PHP variables
PPTX
PHP Powerpoint -- Teach PHP with this
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
PPTX
Licão 13 functions
PDF
PHP 7.0 new features (and new interpreter)
Object-Oriented Programming with PHP (part 1)
Class 2 - Introduction to PHP
Functions in PHP
Php Tutorials for Beginners
PHP Basics
DIG1108 Lesson 6
PHP function
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP Enums - PHPCon Japan 2021
Typed Properties and more: What's coming in PHP 7.4?
PHP 8.1 - What's new and changed
4.2 PHP Function
Operators in PHP
Subroutines
PHP variables
PHP Powerpoint -- Teach PHP with this
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Licão 13 functions
PHP 7.0 new features (and new interpreter)
Ad

Similar to Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney (20)

PPTX
PHP FUNCTIONS AND ARRAY.pptx
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PDF
Web Design EJ3
PDF
php AND MYSQL _ppt.pdf
PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
PPTX
php user defined functions
PDF
Hsc IT 5. Server-Side Scripting (PHP).pdf
PPT
Php basics
PDF
Php tutorial
PDF
PHP-Part3
PPTX
PHP Basics
PPT
PHP Scripting
PPT
PHP-03-Functions.ppt
PPT
PHP-03-Functions.ppt
PDF
WT_PHP_PART1.pdf
PDF
Php Crash Course - Macq Electronique 2010
PPTX
function in php using like three type of function
PDF
Web 8 | Introduction to PHP
PDF
Lecture2_IntroductionToPHP_Spring2023.pdf
PHP FUNCTIONS AND ARRAY.pptx
Introduction to PHP_ Lexical structure_Array_Function_String
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
Web Design EJ3
php AND MYSQL _ppt.pdf
Php my sql - functions - arrays - tutorial - programmerblog.net
php user defined functions
Hsc IT 5. Server-Side Scripting (PHP).pdf
Php basics
Php tutorial
PHP-Part3
PHP Basics
PHP Scripting
PHP-03-Functions.ppt
PHP-03-Functions.ppt
WT_PHP_PART1.pdf
Php Crash Course - Macq Electronique 2010
function in php using like three type of function
Web 8 | Introduction to PHP
Lecture2_IntroductionToPHP_Spring2023.pdf
Ad

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
Electronic commerce courselecture one. Pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Big Data Technologies - Introduction.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
Chapter 3 Spatial Domain Image Processing.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Electronic commerce courselecture one. Pdf
Programs and apps: productivity, graphics, security and other tools
Review of recent advances in non-invasive hemoglobin estimation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The Rise and Fall of 3GPP – Time for a Sabbatical?
Big Data Technologies - Introduction.pptx
Building Integrated photovoltaic BIPV_UPV.pdf

Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

  • 1. Anonymous Functions in PHP 5.3 Matthew Weier O’Phinney 26 April 2011
  • 2. But first, some vocabulary
  • 3. Lambdas • From “lambda calculus” 26 April 2011 Anonymous Functions in PHP 5.3 3
  • 4. Lambdas • From “lambda calculus” • Names of functions are merely a “convenience”, and hence all functions are considered anonymous 26 April 2011 Anonymous Functions in PHP 5.3 3
  • 5. Lambdas • From “lambda calculus” • Names of functions are merely a “convenience”, and hence all functions are considered anonymous • Unless you’re using a true functional programming language with first-class functions, most likely you’re simply using anonymous functions, or lambda expressions. 26 April 2011 Anonymous Functions in PHP 5.3 3
  • 6. Closures • A function which includes a referencing environment 26 April 2011 Anonymous Functions in PHP 5.3 4
  • 7. Closures • A function which includes a referencing environment • Each function has its own scope • Allows hiding state 26 April 2011 Anonymous Functions in PHP 5.3 4
  • 8. Closures • A function which includes a referencing environment • Each function has its own scope • Allows hiding state • Differentiating factor is that closures allow binding references that exist at the time of creation, to use when called. 26 April 2011 Anonymous Functions in PHP 5.3 4
  • 9. Anonymous Functions • Any function defined and/or called without being bound to an identifier. • You can assign the function to a variable, but you’re not giving it its own name. 26 April 2011 Anonymous Functions in PHP 5.3 5
  • 11. Functors • Any object defining a __invoke() method. • Object instances can now be called as if they were functions. class Command { public function __invoke($name) { echo "Hello, $name"; } } $c = new Command(); $c(’Matthew’); // "Hello, Matthew" 26 April 2011 Anonymous Functions in PHP 5.3 7
  • 12. Anonymous Functions • new Closure class, which defines __invoke(). 26 April 2011 Anonymous Functions in PHP 5.3 8
  • 13. Anonymous Functions • new Closure class, which defines __invoke(). • __invoke() body is “replaced” with the defined function. 26 April 2011 Anonymous Functions in PHP 5.3 8
  • 14. Anonymous Functions • new Closure class, which defines __invoke(). • __invoke() body is “replaced” with the defined function. • Ability to bind variables via imports, allowing creation of closures. 26 April 2011 Anonymous Functions in PHP 5.3 8
  • 15. Important to know: • Just like normal PHP functions, anonymous functions exist in their own scope. 26 April 2011 Anonymous Functions in PHP 5.3 9
  • 16. Important to know: • Just like normal PHP functions, anonymous functions exist in their own scope. • You cannot import $this. 26 April 2011 Anonymous Functions in PHP 5.3 9
  • 17. Important to know: • Just like normal PHP functions, anonymous functions exist in their own scope. • You cannot import $this. • You cannot alias imported variables. 26 April 2011 Anonymous Functions in PHP 5.3 9
  • 18. Anonymous Function and Closure Syntax
  • 19. Basics • Simply like normal function declaration, except no name: function($value1[, $value2[, ... $valueN]]) { }; 26 April 2011 Anonymous Functions in PHP 5.3 11
  • 20. Assign to variables • Assign functions to variables; don’t forget the semicolon terminator! $greet = function($name) { echo "Hello, $name"; }; $greet(’Matthew’); // "Hello, Matthew" 26 April 2011 Anonymous Functions in PHP 5.3 12
  • 21. Pass as arguments to other callables • Allow other functionality to call the function. function say($value, $callback) { echo $callback($value); } say(’Matthew’, function($name) { return "Hello, $name"; }); // "Hello, Matthew" 26 April 2011 Anonymous Functions in PHP 5.3 13
  • 22. Create closures • Bind variables at creation, and use them at call-time. $log = Zend_Log::factory($config); $logger = function() use($log) { $args = func_get_args(); $log->info(json_encode($args)); }; $logger(’foo’, ’bar’); // ["foo", "bar"] 26 April 2011 Anonymous Functions in PHP 5.3 14
  • 24. Array operations • Sorting (usort, uasort, etc.) • Walking, mapping, reducing • Filtering 26 April 2011 Anonymous Functions in PHP 5.3 16
  • 25. Sorting $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’); usort($stuff, function($a, $b) { return strcasecmp($a, $b); }); // ’Anise’, ’apple’, ’Applesauce’, ’appleseed’ 26 April 2011 Anonymous Functions in PHP 5.3 17
  • 26. Walking • Walking allows you to change the values of an array. 26 April 2011 Anonymous Functions in PHP 5.3 18
  • 27. Walking • Walking allows you to change the values of an array. • If not using objects, then you need to pass by reference in order to alter values. $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’); array_walk($stuff, function(&$value) { $value = strtoupper($value); }); // ’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’ 26 April 2011 Anonymous Functions in PHP 5.3 18
  • 28. Mapping • Mapping performs work on each element, resulting in a new array with the values returned. 26 April 2011 Anonymous Functions in PHP 5.3 19
  • 29. Mapping • Mapping performs work on each element, resulting in a new array with the values returned. $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’); $mapped = array_map(function($value) { $value = strtoupper($value); return $value; }, $stuff); // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’) // $mapped: array(’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’) 26 April 2011 Anonymous Functions in PHP 5.3 19
  • 30. Reducing • “Combine” elements and return a value or data set. 26 April 2011 Anonymous Functions in PHP 5.3 20
  • 31. Reducing • “Combine” elements and return a value or data set. • Return value is passed as first argument of next call. 26 April 2011 Anonymous Functions in PHP 5.3 20
  • 32. Reducing • “Combine” elements and return a value or data set. • Return value is passed as first argument of next call. • Seed the return value by passing a third argument to array_reduce(). $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’); $reduce = array_reduce($stuff, function($count, $input) { $count += substr_count($input, ’a’); return $count; }, 0); // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’) // $reduce: 3 26 April 2011 Anonymous Functions in PHP 5.3 20
  • 33. Filtering • Return only the elements that evaluate to true. 26 April 2011 Anonymous Functions in PHP 5.3 21
  • 34. Filtering • Return only the elements that evaluate to true. • Often, this is a form of mapping, and used to trim a dataset to only those of interest prior to reducing. $stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’); $reduce = array_reduce($stuff, function($count, $input) { $count += substr_count($input, ’a’); return $count; }, 0); // $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’) // $reduce: 3 26 April 2011 Anonymous Functions in PHP 5.3 21
  • 35. String operations • Regular expressions (preg_replace_callback) 26 April 2011 Anonymous Functions in PHP 5.3 22
  • 36. String operations • Regular expressions (preg_replace_callback) • Currying arguments 26 April 2011 Anonymous Functions in PHP 5.3 22
  • 37. preg_replace_callback() • Allows you to transform captured matches. $string = "Today’s date next month is " . date(’Y-m-d’); $fixed = preg_replace_callback(’/(d{4}-d{2}-d{2})/’, function($matches) { $date = new DateTime($matches[1]); $date->add(new DateInterval(’P1M’)); return $date->format(’Y-m-d’); }, $string); // "Today’s date next month is 2011-05-26" 26 April 2011 Anonymous Functions in PHP 5.3 23
  • 38. Currying arguments • In some cases, you may want to provide default arguments: 26 April 2011 Anonymous Functions in PHP 5.3 24
  • 39. Currying arguments • In some cases, you may want to provide default arguments: • To reduce the number of arguments needed. 26 April 2011 Anonymous Functions in PHP 5.3 24
  • 40. Currying arguments • In some cases, you may want to provide default arguments: • To reduce the number of arguments needed. • To supply values for optional arguments. 26 April 2011 Anonymous Functions in PHP 5.3 24
  • 41. Currying arguments • In some cases, you may want to provide default arguments: • To reduce the number of arguments needed. • To supply values for optional arguments. • To provide a unified signature for callbacks. 26 April 2011 Anonymous Functions in PHP 5.3 24
  • 42. Currying arguments • In some cases, you may want to provide default arguments: • To reduce the number of arguments needed. • To supply values for optional arguments. • To provide a unified signature for callbacks. $hs = function ($value) { return htmlspecialchars($value, ENT_QUOTES, "UTF-8", false); }; $filtered = $hs("<span>Matthew Weier O’Phinney</span>"); // "&lt;span&gt;Matthew Weier O&#039;Phinney&lt;/span&gt;" 26 April 2011 Anonymous Functions in PHP 5.3 24
  • 44. References • Variables passed to callbacks, either as arguments or imports, are not passed by reference. 26 April 2011 Anonymous Functions in PHP 5.3 26
  • 45. References • Variables passed to callbacks, either as arguments or imports, are not passed by reference. • Use objects, or 26 April 2011 Anonymous Functions in PHP 5.3 26
  • 46. References • Variables passed to callbacks, either as arguments or imports, are not passed by reference. • Use objects, or • Pass by reference 26 April 2011 Anonymous Functions in PHP 5.3 26
  • 47. References • Variables passed to callbacks, either as arguments or imports, are not passed by reference. • Use objects, or • Pass by reference $count = 0; $counter = function (&$value) use (&$count) { if (is_int($value)) { $count += $value; $value = 0; } }; $stuff = array(’foo’, 1, 3, ’bar’); array_walk($stuff, $counter); // $stuff: array(’foo’, 0, 0, ’bar’) // $count: 4 26 April 2011 Anonymous Functions in PHP 5.3 26
  • 48. Mixing with other callables Problems and considerations: • Closure is an “implementation detail”; typehinting on it excludes other callback types. 26 April 2011 Anonymous Functions in PHP 5.3 27
  • 49. Mixing with other callables Problems and considerations: • Closure is an “implementation detail”; typehinting on it excludes other callback types. • is_callable() tells us only that it can be called, not how. 26 April 2011 Anonymous Functions in PHP 5.3 27
  • 50. Mixing with other callables Problems and considerations: • Closure is an “implementation detail”; typehinting on it excludes other callback types. • is_callable() tells us only that it can be called, not how. • is_callable() && is_object() tells us we have a functor, but omits other callback types. 26 April 2011 Anonymous Functions in PHP 5.3 27
  • 51. Mixing with other callables Three ways to call (1/3): • $o($arg1, $arg2) 26 April 2011 Anonymous Functions in PHP 5.3 28
  • 52. Mixing with other callables Three ways to call (1/3): • $o($arg1, $arg2) • Benefits: speed. 26 April 2011 Anonymous Functions in PHP 5.3 28
  • 53. Mixing with other callables Three ways to call (1/3): • $o($arg1, $arg2) • Benefits: speed. • Problems: won’t work unless we have a functor, closure, or static method call. 26 April 2011 Anonymous Functions in PHP 5.3 28
  • 54. Mixing with other callables Three ways to call (2/3): • call_user_func($o, $arg1, $arg2) 26 April 2011 Anonymous Functions in PHP 5.3 29
  • 55. Mixing with other callables Three ways to call (2/3): • call_user_func($o, $arg1, $arg2) • Benefits: speed, works with all callables. 26 April 2011 Anonymous Functions in PHP 5.3 29
  • 56. Mixing with other callables Three ways to call (2/3): • call_user_func($o, $arg1, $arg2) • Benefits: speed, works with all callables. • Problems: if number of arguments are unknown until runtime, this gets difficult. 26 April 2011 Anonymous Functions in PHP 5.3 29
  • 57. Mixing with other callables Three ways to call (3/3): • call_user_func_array($o, $argv) 26 April 2011 Anonymous Functions in PHP 5.3 30
  • 58. Mixing with other callables Three ways to call (3/3): • call_user_func_array($o, $argv) • Benefits: works with all callables., works with variable argument counts. 26 April 2011 Anonymous Functions in PHP 5.3 30
  • 59. Mixing with other callables Three ways to call (3/3): • call_user_func_array($o, $argv) • Benefits: works with all callables., works with variable argument counts. • Problems: speed (takes up to 6x longer to execute than straight call). 26 April 2011 Anonymous Functions in PHP 5.3 30
  • 60. You cannot import $this • Creative developers will want to use closures to monkey-patch objects. 26 April 2011 Anonymous Functions in PHP 5.3 31
  • 61. You cannot import $this • Creative developers will want to use closures to monkey-patch objects. • You can. You just can’t use $this, which means you’re limited to public methods. 26 April 2011 Anonymous Functions in PHP 5.3 31
  • 62. You cannot import $this • Creative developers will want to use closures to monkey-patch objects. • You can. You just can’t use $this, which means you’re limited to public methods. • Also, you can’t auto-dereference closures assigned to properties. 26 April 2011 Anonymous Functions in PHP 5.3 31
  • 63. Example: Monkey-Patching class Foo { public function __construct() { $self = $this; $this->bar = function () use ($self) { return get_object_vars($self); }; } public function addMethod($name, Closure $c) { $this->$name = $c; } public function __call($method, $args) { if (property_exists($this, $method) && is_callable($this->$method)) { return call_user_func_array($this->$method, $args); } } } 26 April 2011 Anonymous Functions in PHP 5.3 32
  • 64. Serialization • You can’t serialize anonymous functions. 26 April 2011 Anonymous Functions in PHP 5.3 33
  • 66. Aspect Oriented Programming • Code defines “aspects,” or code that cuts across boundaries of many components. 26 April 2011 Anonymous Functions in PHP 5.3 35
  • 67. Aspect Oriented Programming • Code defines “aspects,” or code that cuts across boundaries of many components. • AOP formalizes a way to join aspects to other code. 26 April 2011 Anonymous Functions in PHP 5.3 35
  • 68. Aspect Oriented Programming • Code defines “aspects,” or code that cuts across boundaries of many components. • AOP formalizes a way to join aspects to other code. • Often, you will need to curry arguments in order to maintain signatures. 26 April 2011 Anonymous Functions in PHP 5.3 35
  • 69. Event Management example $front->events()->attach(’dispatch.router.post’, function($e) use ($cache) { $request = $e->getParam(’request’); if (!$request instanceof ZendHttpRequest || !$request->isGet()) { return; } $metadata = json_encode($request->getMetadata()); $key = hash(’md5’, $metadata); $backend = $cache->getCache(’default’); if (false !== ($content = $backend->load($key))) { $response = $e->getParam(’response’); $response->setContent($content); return $response; } return; }); 26 April 2011 Anonymous Functions in PHP 5.3 36
  • 71. References • PHP Manual: http://php.net/functions.anonymous 26 April 2011 Anonymous Functions in PHP 5.3 38