Programming
Article
By Troels Knak-Nielsen

Lexical scope to appear in PHP?

By Troels Knak-Nielsen

I mentioned briefly, in my last post, that Wez Furlong made a patch back in March, that allows a native syntax for creating anonymous functions. This could replace the heinous create_function.

Since then, I brought up Wez’ original patch again on the php-internals lists. This has prompted some hefty debate over the last week. The main argument against approving the patch, seems to be, that one would expect static scoping rules to apply to the anonymous function. After all, this is the case in similar languages, which support anonymous functions. One could only assume, that changing PHP to support this, would be a major undertaking.

One would be wrong, it seems.

Today, Christian Seiler posted a patch to allow lexical scope for anonymous functions. There are a few loose ends, but it appears to work in general. Instead of making all variables follow the static scoping rules, a new keyword (lexical) is introduced. It works similar to global, in that it must be explicitly declared, which variables are lexically scoped. This is how it looks in action:


function getAdder($x) {
  return function ($y) {
    lexical $x;
    return $x + $y;
  };
}
$add2 = getAdder(2);
$add2(8); // return 10

It’s probably a bit early to tell if this will find its way into the language. It’s still just a proposal and it would take some further work to get it right, but at least it appears to be technically possible. We’ll have to wait and see.

Otherwise, there’s just left to wish you all a merry Christmas.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account