Posts Tagged ‘programming’

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.

My mod_rewrite presentation

Friday, April 18th, 2008

Here’s the presentation I put together for last month’s meetup. I hear nobody showed it in my absence, but I thought at least some of you might be interested.

High-Performance javascript: Why Everything You’ve Been Taught is Wrong

Friday, April 18th, 2008

Yeah, we’re a PHP group. But most of the PHP code out there is on the web, and modern web sites rely heavily on Javascript for AJAX & DHTML effects.

This talk from last year’s OSCONconference talks about ways to improve Javascript performance. Some of these techniques are pretty sneaky, and aren’t immediately obvious. But I’ve tried some of them out, and they made a big difference in the how performance was perceived, even if they didn’t make big actual improvements.