I see that the new planned features for PHP 5.4 are: traits, array dereferencing, a JsonSerializable interface and something referred to as 'closure $this support
'
http://en.wikipedia.org/wiki/Php#Release_history
While the others are either immediately clear (JsonSerialiable, array dereferencing) or i looked up the specifics (traits), I am not sure what 'closure $this support' is. I have been unsuccessful googling for it or finding anything about it on php.net
Does anyone know what this is supposed to be?
If i had to guess, it would mean something like this:
$a = 10; $b = 'strrrring';
//'old' way, PHP 5.3.x
$myClosure = function($x) use($a,$b)
{
if (strlen($x) <= $a) return $x;
else return $b;
};
//'new' way with closure $this for PHP 5.4
$myNewClosure = function($x) use($a as $lengthCap,$b as $alternative)
{
if(strlen($x) <= $this->lengthCap)) return $x;
else
{
$this->lengthCap++; //lengthcap is incremented for next time around
return $this->alternative;
}
};
The significance (even if this example is trivial) being that in the past once the closure is constructed the bound 'use' variables are fixed. With 'closure $this support' they are more like members you can mess with.
Does this sound correct and/or close and/or reasonable? Does anyone know what this 'closure $this support' means?
This was already planned for PHP 5.3, but
It indeed means you can refer to the object instance (live demo)
For a discussion, see the PHP Wiki
and for historic interest:
One thing that Gordon missed is re-binding of
$this
. While what he described is the default behaviour, it is possible to re-bind it.Example
The closures
bindTo
instance method (alternatively use the staticClosure::bind
) will return a new closure with$this
re-bound to the value given. The scope is set by passing the second argument, this will determine visibility of private and protected members, when accessed from within the closure.Just building on the other answers here, I think this example will demonstrate what is possible PHP 5.4+:
see: https://eval.in/private/3183e0949dd2db
Building on @Gordon's answer it is posible to mimic some hacky aspects of closure-$this in PHP 5.3.