I've been thinking about this on and off today too.
Something along the lines of the following is more in the PHP spirit:

$ver = phpversion();
$fancyVer = function () { lexical $ver; return "PHP $ver"; };

Where "lexical" is a keyword that means "inherit this variable from the current lexical scope". I'm not suggesting that this is a good name for the keyword, it's just something that springs to mind.

So, given some way to explicitly reference the scope where the function was "defined", what happens when you call $fancyVer after that scope has gone away:

function doSomething() {
  $ver = phpversion();
  return function () { lexical $ver; return "PHP $ver"; };
}
$func = doSomething();
$func(); # the doSomething() scope (hash table) doesn't exist any more

This could perhaps be solved by taking a reference to $ver when the function is bound, but I don't know enough about the ZE to understand the implications of that; it would probably require a bit more state tracking per zend_function so that we know that we need to do that step during binding.

--Wez.

On Mar 19, 2007, at 3:25 PM, Sean Coates wrote:

If it would create anonymous function compile-time, it would be a big
advantage to Wez's patch because then this function could be cached.
Thinking about this, maybe it is the reason enough to do this even if
it's not real closure.

On mulling this over a bit more, other than quick one-off callbacks
(which would definitely benefit from avoiding compile on every request),
one of the key reasons to use create_function() is actually to create
dynamic functions:

$fancyVer = create_function('', 'return "PHP " . phpversion();');
// could be optimized as:
$fancyVer = create_function('', 'return "PHP ' . phpversion() .'";');

(the latter only calls phpversion() at declaration, not each time the
lambda runs)

Since phpversion() is available globally, this isn't a problem. But what
happens if we want to use a variable, instead?

$ver = phpversion();
$fancyVer = create_function('', "return 'PHP $ver';");
// this currently works ^

How would this be rewritten, though?
$ver = phpversion();
$fancyVer = function () { return "PHP $ver"; };

where would $ver come from? the parent scope? the lambda's local scope?
what if it's defined in both places?

S



--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to