2017-09-21 58 views
1

我这是工作正常的代码库的一部分,下面的PHP方法的参数:

<?php 
class HooksTest extends DrupalTestCase { 
    public function testPageAlterIsLoggedIn() { 
    $this->drupal->shouldReceive('userIsLoggedIn') 
     ->once() 
     ->andReturn(TRUE); 
    $this->drupal->shouldReceive('drupalPageIsCacheable') 
     ->once() 
     ->andReturnUsing(function ($this) { 
     return $this; 
     }); 
    $page = []; 
    $cacheable = $this->object->pageAlter($page); 
    $this->assertFalse($cacheable); 
    } 
} 

的代码是通过所有的CI测试之前(使用phpunit )。

但是现在,当我通过php HooksTest.php调用该文件,我已经得到了以下错误:

PHP Fatal error: Cannot use $this as parameter in HooksTest.php on line 11

Fatal error: Cannot use $this as parameter in HooksTest.php on line 11

我用PHP 7.1,7.2和相同的问题进行测试。我相信它在PHP 5.6中工作。

如何将上面的代码转换为具有相同的含义?

从函数参数中删除$this应该足够吗?

+0

使用self :: maybe? – rak007

+0

我不认为你可以将'$ this'传递给' - >和返回函数中的函数(function($ this){' – aynber

+0

这是通过所有测试的现有代码的一部分,所以这不是我的发明。我知道它工作正常,现在在PHP 7.x下失败了。 – kenorb

回答

3

只跳过$this的说法,改变

function ($this) { 
    return $this; 
} 

function() { 
    return $this; 
} 

实例#5自动上Anonymous functions页的$this结合:

<?php 
class Test 
{ 
    public function testing() 
    { 
     return function() { 
      var_dump($this); 
     }; 
    } 
} 
$object = new Test; 
$function = $object->testing(); 
$function(); 
?> 
0

是的,正如先前陈述的aynber,你不能将$ this作为函数参数传递。通过这样做,你基本上已经宣布了它。您应该将其作为函数参数删除。

2

如果您希望其工作方式与以前相同,则不应删除$this作为参数。您应该将参数的名称更改为其他名称,并在闭包中更改相应的变量名称。

通过PHP 5.6,在类方法的闭包中使用$this作为参数将掩盖引用父对象的$this。例如:

class Example 
{ 
    public function test ($param) { 
     $closure = function ($whatever) {  // $this not used as parameter 
      return $this;      // $this refers to the Example object 
     }; 
     return $closure($param); 
    } 

    public function test2 ($param) { 
     $closure = function($this) {   // $this used as parameter 
      return $this;      // $this no longer refers to Example object 
     }; 
     return $closure($param); 
    } 

} 

$ex = new Example; 
$not_masked = $ex->test('foo'); 
$masked = $ex->test2('foo'); 

var_dump($not_masked, $masked); 

Working example on 3v4l.org

在PHP 5.6,$masked将字符串 '富',$ex对象。

根据你可以在3v4l.org链接看到的不同版本的输出,从7.0.0-7.0.6开始有一个短暂的时间段,其中$this参数明显被忽略,而偏向于对象自身-参考。我假设他们在后面的版本中不允许使用$this作为参数,以避免在闭合范围中实际引用的含糊不清。

看起来这只是混淆了原始代码中的命名。为了使它像以前一样工作:

->andReturnUsing(function ($anyOtherName) { 
    return $anyOtherName; 
});