从闭包中访问私有变量 [英] Accessing private variables from within a closure
问题描述
我试图引用一个闭包中的对象的私有变量。下面的代码似乎工作,但它抱怨致命错误:不能访问self ::当在第12行test.php没有活动的范围
和致命错误:在第20行的test.php中不在对象上下文中时使用$ this
I'm trying to reference a private variable of an object from within a closure. The code below would seem to work, but it complains Fatal error: Cannot access self:: when no class scope is active in test.php on line 12
and Fatal error: Using $this when not in object context in test.php on line 20
.
任何想法如何完成结果使用闭包,同时保持变量私有和没有帮助函数(击败整个想法的私有变量)。
Any ideas how to accomplish the same results using a closure while keeping the variables private and without making helper functions (defeating the whole idea of a private variable).
class MyClass
{
static private $_var1;
private $_var2;
static function setVar1( $value )
{
$closure = function () use ( $value ) {
self::$_var1 = $value;
};
$closure();
}
function setVar2( $value )
{
$closure = function () use ( $value ) {
$this->_var2 = $value;
};
$closure();
}
}
MyClass::setVar1( "hello" ); //doesn't work
$myclass = new MyClass;
$myclass->setVar2( "hello" ); //doesn't work
推荐答案
注意,此答案最初适用于 PHP5.3 及更早版本,现在可以使用。有关当前信息,请参阅此答案。
Edit to note, this answer was originally meant for PHP5.3 and earlier, it's possible now. For current information, see this answer.
这是不可能的。
但是,您可以使用引用:
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" );
这篇关于从闭包中访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!