Edit to note, this answer was originally meant for PHP5.3 and earlier, it's possible now. For current information, see this answer.
This is not directly possible. In particularly, closures have no associated scope, so they cannot access private and protected members.
You can, however, use references:
<?php
class MyClass
{
static private $_var1;
private $_var2;
static function setVar1( $value )
{
$field =& self::$_var1;
$closure = function () use ( $value, &$field ) {
$field = $value;
};
$closure();
}
function setVar2( $value )
{
$field =& $this->_var2;
$closure = function () use ( $value, &$field ) {
$field = $value;
};
$closure();
}
}
MyClass::setVar1( "hello" );
$myclass = new MyClass;
$myclass->setVar2( "hello" );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…