[Haskell-cafe] Lambda and closures in PHP -- could someone please comment?

Alexander Wagner waqner at gmx.net
Thu Jun 19 18:54:51 EDT 2008

CC to Christian Seiler

On Wednesday 18 June 2008, Luke Palmer wrote:
> * A closure must be able to call itself recursively (via a
> higher-order function typically)

I see two ways a closure might get a hold of itself, in order it can call 

$f = function () {
  lexical $whatever;
  lexical $f; //get yourself by lexical scope
  return $f();

$g = function ($g) {  //get yourself by parameter
  lexical $whatever;
  return $g($g);

Getting the first version to work is somewhat tricky in a non-lazy language, 
but it would be nice to have. The second should definately work.
I guess I'll download the patch and try.

> * I would recommend only saving $this in the op_array structure if the
> closure actually references $this -- if that is possible to deduce at
> the time. Otherwise you might run into unexpected poor memory
> performances in certain cases.

Agreed. A closure created inside an object should be able to outlive the 
object by not holding a reference to it.
Since many PHP programmers put pretty much all of their functions into classes 
for style reasons, which would mean most closures are created in the context 
of an object, implicitly referencing $this might prevent a lot of objects 
from being garbage-collected. Also, doesn't that turn all lambdas defined 
inside an object into closures, which are heavier?

Between always referencing $this in a lamda and requiring "lexical $this", the 
latter seems like the smaller evil to me. 


More information about the Haskell-Cafe mailing list