Simple PHP closure/lamda/anonymous function usage.

This is a fun little example of the new Closure features in php.

We can go a little further, and do like this.

An issue that comes up is, how do I get the $this variable in there. The short answer is, you don’t. You can finaigle it after a fashion, but it’s just ugly.

The issue is, people want the $this var, because they want to be able to manipulate the values, in a permanent fashion, or do something else. How you accomplish it, in a pretty way is:

1. Give up the ghost, you can’t have $this, it’s just a word, pick a different word.
2. standardize the new $this word
3. pass that word as a reference.

So, we end up modifying the code a little:

Then we can do stuff like this:

Well, that’s some PHP Closure funness.

About Jason

I am a 31 year old programmer living in the south of France. I currently work actively in the fields of Ruby/PHP/Javascript and server/website administration.
This entry was posted in OOP, PHP Tutorials, PHP/MySQL, Topics and tagged , , . Bookmark the permalink.