在php(5.3!)中的匿名函数中使用$this及其受保护的变量

在php(5.3!)中的匿名函数中使用$this及其受保护的变量,php,Php,您知道它在Php 5.3中不起作用,但在5.4中起作用,因此有一点变通方法: $thisObj = $this; $thisObj->parameters = 1; // works! $result = $this->method(function() use ($returnThisIndex, $thisObj) { $thisObj->parameters = 1; // wont work! Its a protected variable! }); 这里我

您知道它在Php 5.3中不起作用,但在5.4中起作用,因此有一点变通方法:

$thisObj = $this;
$thisObj->parameters = 1; // works!
$result = $this->method(function() use ($returnThisIndex, $thisObj) {
    $thisObj->parameters = 1; // wont work! Its a protected variable!
});

这里我把一个函数传递给一个方法。问题是,“parameters”是一个受保护的变量,因此在这个方法中仍然看不到它。那么如何解决这个问题呢?

在类中使用设置函数

public function setParam($param) {
     $this->parameters = $param;
}
然后在匿名函数中

$thisObj->setParam(1);