Now, before you say, they are anonymous functions, I would like to state that, I know it already. What I can't understand, is their importance and usage. If someone can explain or provide a simple HelloWorld using closures, demonstrating their purpose, it would be very nice. Thanks
ref: http://php.net/manual/en/functions.anonymous.php they let you create small functions without names so, for me, no need to come up with unique names. I wouldn't use them if the function would be needed in multiple places but for one offs it's quite handy.
If I was smart enough to want to learn about closures, I think it would be safe to assume, I have also, seen the reference manual. Having said that, I was just looking for a simple tutorial, here.
Edit: Just noticed this was the JavaScript section. NVM. Demo: http://www.debug.us/stuff/closure.php <?php //simple combat example using closures for moves header('Content-Type: text/plain'); class Monster { private $mName; private $mHealth = 0; private $mAttack = 0; private $mDefense = 0; private $mMoves = null; public function __construct($name,$health,$attack,$defense) { $this->mName = $name; $this->mHealth = $health; $this->mAttack = $attack; $this->mDefense = $defense; $this->mMoves = []; } public function learnMove($name, $func) { $this->mMoves[$name] = $func; } public function attack($target) { $index = array_rand($this->mMoves); $response = $this->mMoves[$index]($target,$this); echo $this->mName,' used ',$index,' on ',$target->getName(),'. ',$response; } public function defend($opponent,$pulse,$piercing=false) { if(!$piercing) $pulse = max($pulse-$this->mDefense,1); $this->mHealth -= $pulse; return $this->mName.' received '.$pulse.' damage.'; } public function getName() { return $this->mName; } public function getHealth() { return $this->mHealth; } public function getAttack() { return $this->mAttack; } public function getDefense() { return $this->mDefense; } } $endeavor = function($target,$opponent) { $difference = $target->getHealth()-$opponent->getHealth(); return $target->defend($opponent,max($difference,0),true); }; $slap = function($target,$opponent) { $maxDamage = $opponent->getAttack(); return $target->defend($opponent,$maxDamage); }; $rage = function($target,$opponent) { return $target->defend($opponent,10,true); }; $punch = function($target,$opponent) { return $target->defend($opponent,rand(1,15)); }; $puppy = new Monster('Cutsie',50,10,1); $kitty = new Monster('Meow',45,12,2); $puppy->learnMove('Endeavor',$endeavor); $puppy->learnMove('Slap',$slap); $kitty->learnMove('Rage',$rage); $kitty->learnMove('Punch',$punch); do { echo $kitty->attack($puppy),"\n"; if($puppy->getHealth()>0) echo $puppy->attack($kitty),"\n"; } while($kitty->getHealth()>0 && $puppy->getHealth()>0); PHP: