PHP anonymous functions and closures


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. $multiply = function($multiplier)
  4. {
  5. return function($x) use ($multiplier)
  6. {
  7. return $x * $multiplier;
  8. };
  9. };
  10.  
  11. // $mul5 now contains a function that returns a number multiplied by 5
  12. $mult5 = $multiply(5);
  13.  
  14. // $mul7 contains a function that returns a number multiplied by 7
  15. $mult7 = $multiply(7);
  16.  
  17. echo $mult5(5);
  18. echo $mult7(5);
  19.  
  20. // Output-
  21. // 25
  22. // 35
  23.  
  24. ?>

URL: http://www.codediesel.com/php/anonymous-functions-in-php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.