Posts Tagged ‘development’

PHP is getting closures!

Tuesday, July 22nd, 2008

I’ve seen very little from PHP that got me excited lately.  So, imagine how excited I am to hear that closures are coming to PHP 5.3!

If you’ve done a lot with today’s popular Javascript libraries like jQuery and Prototype, you’ve no doubt come across closures.  They’re little self-contained functions that can be passed around like variables.  For example, jQuery’s fadeIn() method takes a function as its second parameter, and calls it when the target has faded in.  With a traditional coding style, you may have written something like this:

 

function doStuff1()
{
	// do some stuff...

	$('#mydiv').fadeIn('normal', doStuff2);

	// do some more stuff...
}

function doStuff2()
{
	echo "hello world!";
}

This works, but there’s a visual disconnect between what happens in the middle of doStuff1() and what happens in doStuff2(). And, when you start reading doStuff2(), you don’t have any context for what’s happening (unless you left really good comments). If doStuff2() is used in more than one place, you have a justification for keeping it a separate function. But if it’s only used this one time, a closure is the way to go:

function doStuff1()
{
	// do some stuff...

	$('#mydiv').fadeIn('normal', function() {
		echo "hello world!";
	});

	// do some more stuff...
}

This code is more compact, and it makes it clear that the echo statement is related to the fadeIn() call.

I use closures a lot in my Javascript coding, and I’m sure I’ll be using them a lot in PHP once 5.3 is widespread.