code_junkie

Closures in PHP… what, precisely, are they and when would you need to use them?

Nov 11th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. function config_parser()
  2. {
  3. // Do some code here
  4. // $hash_method is in config_parser() local scope
  5. $hash_method = 'multiply';
  6.  
  7. if ($hashing_enabled)
  8. {
  9. function do_hash_method($var)
  10. {
  11. // $hash_method is from the parent's local scope
  12. if ($hash_method == 'multiply')
  13. return $var * $var;
  14. else
  15. return $var ^ $var;
  16. }
  17. }
  18. }
  19.  
  20.  
  21. function hashme($val)
  22. {
  23. // do_hash_method still knows about $hash_method
  24. // even though it's not in the local scope anymore
  25. $val = do_hash_method($val)
  26. }
  27.  
  28. function replace_spaces ($text) {
  29. $replacement = function ($matches) {
  30. return str_replace ($matches[1], ' ', ' ').' ';
  31. };
  32. return preg_replace_callback ('/( +) /', $replacement, $text);
  33. }
  34.  
  35. class ConfigurableEncoder{
  36. private $algorithm = 'multiply'; //default is multiply
  37.  
  38. public function encode($x){
  39. return call_user_func(array($this,$this->algorithm),$x);
  40. }
  41.  
  42. public function multiply($x){
  43. return $x * 5;
  44. }
  45.  
  46. public function add($x){
  47. return $x + 5;
  48. }
  49.  
  50. public function setAlgorithm($algName){
  51. switch(strtolower($algName)){
  52. case 'add':
  53. $this->algorithm = 'add';
  54. break;
  55. case 'multiply': //fall through
  56. default: //default is multiply
  57. $this->algorithm = 'multiply';
  58. break;
  59. }
  60. }
  61. }
  62.  
  63. $raw = 5;
  64. $encoder = new ConfigurableEncoder(); // set to multiply
  65. echo "raw: $rawn"; // 5
  66. echo "multiply: " . $encoder->encode($raw) . "n"; // 25
  67. $encoder->setAlgorithm('add');
  68. echo "add: " . $encoder->encode($raw) . "n"; // 10
Add Comment
Please, Sign In to add comment