NYCPHP Meetup

NYPHP.org

[nycphp-talk] Getting Closure - on PHP Closures and 5.3

John Campbell jcampbell1 at gmail.com
Fri Jul 16 22:57:42 EDT 2010


On Fri, Jul 16, 2010 at 10:21 PM, David Krings <ramons at gmx.net> wrote:
> Uhm, for the ones like me who have no clue what this means, any pointers
> available that explain closures?

You can read about closures until you are blue in the face.  The first
thing you have to grock is first-class functions.  Which basically
means a variable can be a function.  We normally think of variables as
"data", but there is no reason you can't store a procedure in a
variable.  Once you understand that functions are just another type of
variable, then you can write functions that create other functions.
e.g. you can return a function from a function.  The following code
illustrates the concept, and is valid php 5.3

<?php

$add1 = function($val) {
	echo $val+1,"\n";
};

$add1(5); // prints 6

function makeAdder($num) {
	return function($how_many) {
		echo $how_many + $num, "\n";
	};
}

$add6 = makeAdder(6);

$add6(3);  // prints 3, but why?

function makeAdderClosure($num) {
	return function($how_many) use ($num) {
		echo $how_many + $num, "\n";
	};
}

$add5 = makeAdderClosure(5);

$add5(3);  // prints 8;

$add4= makeAdderClosure(4);

$add4(4);  // prints 8;



More information about the talk mailing list