Posted By

karlhorky on 11/28/10


Tagged

php function lambda parameter parameters Pass Anonymous anonymousfunction anonymousfunctions lambdas 53


Versions (?)

Pass anonymous function (lambda) as parameter prior to PHP 5.3


 / Published in: PHP
 

URL: http://stackoverflow.com/questions/3809405/converting-code-with-anonymous-functions-to-php-5-2#answer-3809564

Prior to 5.3, anonymous functions (lambdas) can be achieved via the create_function PHP function. This allows for the anonymous functions to be passed as parameters to another function as well, illustrated in this example snippet.

  1. <?php
  2. // Pass anonymous function (lambda) as parameter prior to PHP 5.3
  3.  
  4. function processAnonymousFunction($a = NULL) {
  5. // If parameter passed is a string and a function by that name exists (as
  6. // should exist with create_function), call the function
  7. if (is_string($a) && function_exists($a)) {
  8. $a();
  9. } else {
  10. echo 'No valid anonymous function passed!';
  11. }
  12. }
  13.  
  14. // Outputs: 'Anonymous function (lambda) passed successfully!'
  15. processAnonymousFunction(create_function('','echo "Anonymous function (lambda) passed successfully!";'));
  16.  
  17. echo '<br>';
  18.  
  19. // Outputs: 'No valid anonymous function passed!'
  20. processAnonymousFunction();
  21. ?>

Report this snippet  

You need to login to post a comment.